使用HTTP方式发送请求及json数据的接收和解析

这篇具有很好参考价值的文章主要介绍了使用HTTP方式发送请求及json数据的接收和解析。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

目录

需求

请求端

1,添加依赖

2,请求对象

3,请求工具类

4,请求测试(事先开启接收端的服务)

接收端

数据请求模拟


需求

本项目需要通过向对端第三方项目发送一个http的post类型的请求,并且指定了一些请求字段,数据传输采用了json,对请求头没有其他特殊要求,所以这里写了一个demo作为参考

请求端

1,添加依赖

这里我在对json进行发送和解析的时候,我采用了fastjson工具。

        <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

2,请求对象

这个对象主要的作用就是将需要发送的参数作为对象的属性然后可以将对象直接转化为json,这种请求在请求参数的类型不一致的时候可以使用(Long,String,DateTIme等等)

public class RequestChange {

    private Long accNum;

    private String servPwdResetChnl;

    private String servPwdResetTime;
 
    private String system;

    //set和get方法  省略.....
}

3,请求工具类

这里多注意代码中这个语句,之前一直没有添加 "UTF-8"这个参数,导致请求的中文参数全是???。如图所示

json 头 http,工作记录,java,http,idea,数据仓库

// 设置请求参数
			StringEntity se = new StringEntity(jsonstr,"UTF-8");
import org.apache.http.*;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URLEncoder;

@Component
public class HttpUtil {
	
	/**
	 * httpClient get请求
	 * 
	 * @param url 请求url

	 * @param jsonstr 请求实体 json/xml提交适用
	 * @return 可能为空 需要处理
	 * @throws Exception
	 *
	 */
	public static String sendHttpGet(String url, String jsonstr)
			throws Exception {
		String result = "";
		CloseableHttpClient httpClient = null;
		try {
			httpClient = HttpClients.createDefault();
			
			if(null != jsonstr && !"".equals(jsonstr)) {
				jsonstr = URLEncoder.encode(jsonstr, "UTF-8");
				url = url + "?req=" + jsonstr;
			}
			
			System.out.println("url------------" + url);
			HttpGet httpGet = new HttpGet(url);

			// 设置头信息
			httpGet.addHeader("Content-Type", "application/json;charset=utf-8");
			httpGet.addHeader("Accept", "application/json;charset=utf-8");

			HttpResponse httpResponse = httpClient.execute(httpGet);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				HttpEntity resEntity = httpResponse.getEntity();
				result = EntityUtils.toString(resEntity);
			} else {
				readHttpResponse(httpResponse);
			}
		} catch (Exception e) {
			throw e;
		} finally {
			
			if (httpClient != null) {
				httpClient.close();
			}
		}
		return result;
	}

	/**
	 * httpClient post请求
	 * 
	 * @param url 请求url

	 * @param jsonstr 请求实体 json/xml提交适用
	 * @return 可能为空 需要处理
	 * @throws Exception
	 *
	 */
	public static String sendHttpPost(String url, String jsonstr)
			throws Exception {
		String result = "";
		CloseableHttpClient httpClient = null;
		try {
			httpClient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);

			// 设置头信息
			httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
			httpPost.addHeader("Accept", "application/json;charset=utf-8");

			System.out.println("放入到请求体参数为="+jsonstr);

			// 设置请求参数
			StringEntity se = new StringEntity(jsonstr,"UTF-8");
			httpPost.setEntity(se);

			HttpResponse httpResponse = httpClient.execute(httpPost);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				HttpEntity resEntity = httpResponse.getEntity();
				result = EntityUtils.toString(resEntity);
			} else {
				readHttpResponse(httpResponse);
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (httpClient != null) {
				httpClient.close();
			}
		}
		return result;
	}
	
	public static String readHttpResponse(HttpResponse httpResponse)
			throws ParseException, IOException {
		StringBuilder builder = new StringBuilder();
		// 获取响应消息实体
		HttpEntity entity = httpResponse.getEntity();
		// 响应状态
		builder.append("status:" + httpResponse.getStatusLine());
		builder.append("headers:");
		HeaderIterator iterator = httpResponse.headerIterator();
		while (iterator.hasNext()) {
			builder.append("\t" + iterator.next());
		}
		// 判断响应实体是否为空
		if (entity != null) {
			String responseString = EntityUtils.toString(entity);
			builder.append("response length:" + responseString.length());
			builder.append("response content:"
					+ responseString.replace("\r\n", ""));
		}
		return builder.toString();
	}

	public static void main(String[] args) throws Exception {
		System.out.println(sendHttpGet("http://127.0.0.1:8080//AccountSynchro", "{\"login\" : \"\", \"alias\" : \"153057123231021\", \"passwd\" : \"122323456\"}"));

	}
}

4,请求测试(事先开启接收端的服务)

主要就是将请求对象进行赋值,然后通过fastJson将对象转化为将json数据然后进行请求,

这里需要注意的是接受请求的时候 ,这里我进行了一个格式话的接受json数据的解析,如果不能

//解析返回的json字符串  返回的数据为="{\"msg\":\"fail\",\"data\":\"没啥数据\"}"  带有转义字符需要进行重新编译

        Object parse = JSON.parse(resultJson);

        String s2 = parse.toString();

        RespChange respChange = JSON.parseObject(s2, RespChange.class);

        System.out.println(respChange.getMsg());

全部请求和解析json代码


@SpringBootTest(classes = UagApplication.class)
public class HttpTest {

    //获取到传送工具类
//    @Autowired
//    private HttpUtil httpUtil;


    //获取到请求路径
    @Value("${Changes.remind.path}")
    private String remindPath="";


    @Autowired
    private ProvincialEvents provincialEvents;


    @Autowired
    private ITransactionIdManager transIdManager = null;



    @Test
    public  void  test1() throws Exception {
        System.out.println("hello world");

        //测试发送 json数据 多个参数不同类型

        long accNum=1111;

        String system="uam";

        //将参数字段转化为字符串 创建一个对象

        RequestChange requestChange = new RequestChange();

        requestChange.setAccNum(accNum);
       //requestChange.setServPwdResetChnl(servPwdResetChnl);
        requestChange.setServPwdResetChnl("好的");
        //创建当前时间


        Date date = Calendar.getInstance().getTime();

        DateFormat dateFormat = new SimpleDateFormat("YYYYMMddHHmmss");

        String format = dateFormat.format(date);

        requestChange.setServPwdResetTime(format);

        requestChange.setSystem(system);

        System.out.println("转化后的时间为="+requestChange.getServPwdResetTime());



        //将对象转化为json

        String s = JSON.toJSONString(requestChange);

        System.out.println("对象转化为json之后的格式="+s);

        if (StringUtil.isEmptyString(remindPath)){
            System.out.println("路径没有获取到"+remindPath);
        }
        System.out.println("路径获取到="+remindPath);

        String resultJson = HttpUtil.sendHttpPost(remindPath, s);

        System.out.println("返回的数据为="+resultJson);


        //解析返回的json字符串  返回的数据为="{\"msg\":\"fail\",\"data\":\"没啥数据\"}"  带有转义字符需要进行重新编译

        Object parse = JSON.parse(resultJson);

        String s2 = parse.toString();

        RespChange respChange = JSON.parseObject(s2, RespChange.class);

        System.out.println(respChange.getMsg());


    }

}

接收端

接收请求发过来的json数据,并且可以解析成自己需要格式(String,Map,对象)

@RestController
@RequestMapping(value ="/test")
public class TestHttpController {

    @RequestMapping(value = "/http",method=RequestMethod.POST)
    public String  testHttp(@RequestBody JSONObject json){
        

        //解析json数据,获取到每一个属性对应的值
        System.out.println(json.getString("accNum"));
        System.out.println(json.getString("servPwdResetChnl"));
        System.out.println(json.getString("servPwdResetTime"));
        System.out.println(json.getString("system"));
        
        
        //返回响应json字符串
        HashMap<String, String> map = new HashMap<>();
        map.put("msg","success");
        map.put("data","没啥数据");
        String s = JSON.toJSONString(map);
        return  s;

    }

}

数据请求模拟

1,开始接收端服务

2,开启请求端服务发送请求

json 头 http,工作记录,java,http,idea,数据仓库

json 头 http,工作记录,java,http,idea,数据仓库 

 

参考文章:

json如何传输数据 

(31条消息) Java中使用JSON数据传递_杀神lwz的博客-CSDN博客_java传递json格式数据

接受方如何解析

(31条消息) Java接收json参数_詹Sir(开源字节)的博客-CSDN博客_java接收json对象文章来源地址https://www.toymoban.com/news/detail-799037.html

到了这里,关于使用HTTP方式发送请求及json数据的接收和解析的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • vue使用axios发送post请求携带json body参数,后端使用@RequestBody进行接收

    最近在做自己项目中,做一个非常简单的新增用户场景,但是使用原生axios发送post请求的时候,还是踩了不少坑的。 唉,说多了都是泪,小小一个新增业务,在自己前后端一起开发的时候,硬是搞了好久。 下面就把问题总结分享下,防止后人再踩坑。 首先先看下我的接口定

    2024年02月02日
    浏览(37)
  • java http get post 和 发送json数据请求

    浏览器请求效果       main调用  

    2024年02月16日
    浏览(34)
  • http发送和接收图片json文件

    1、先将图片转换为base64格式 2、将数据以json格式进行发送 其中 ImgInfo 类为: 上述代码中json数据有五个部分:image为图片数据,level是告警等级,rtsp为数据流地址,type是算法类型,label是算法标签等,所以数据发送为这五个内容。 HttpServer.cpp如下:   HttpServer.h如下: httpu

    2024年02月07日
    浏览(25)
  • C#请求访问HTTP+JSON数据的解析

    最近工作客户需要一个HTTP的Mes需求,所以自己去学习了C#请求HTTP的方法以及JSON数据的解析方法,总结出了点经验,以便后续自己找起来方便一点,故在此写一篇文章。 下面我用一个聚合数据提供的天气预报API接口来阐述请求HTTP和JSON数据解析的功能; 先看API文档这么访问数

    2024年02月12日
    浏览(30)
  • 【Jmeter】信息头管理器(HTTP Header Manager) - 发送Post请求数据为json格式

    将 json 格式 请求数据输入 HTTP 请求 中的 Body Data (消息体数据 / 请求入参) 右击 Thread (线程组) 鼠标移至 Add (添加) → Config Element (配置元件) 点击 HTTP Header Manager (HTTP信息头管理器) 即可完成信息头管理器新建 进入 HTTP Header Manager (HTTP信息头管理器) 页面 点击下方 Add (添加) Nam

    2024年02月07日
    浏览(30)
  • C/C++ 发送与接收HTTP/S请求

    HTTP(Hypertext Transfer Protocol)是一种用于传输超文本的协议。它是一种无状态的、应用层的协议,用于在计算机之间传输超文本文档,通常在 Web 浏览器和 Web 服务器之间进行数据通信。HTTP 是由互联网工程任务组(IETF)定义的,它是基于客户端-服务器模型的协议,其中客户端

    2024年02月05日
    浏览(39)
  • 138. 第三方系统或者工具通过 HTTP 请求发送给 ABAP 系统的数据,应该如何解析

    本教程第 37 篇文章,我们介绍了如何在 SAP ABAP 系统 SICF 事务码 里,开发一段 ABAP 代码,用来响应通过浏览器或者第三方工具,比如 curl,Postman 发起的 HTTP 请求。 31. 如何让 ABAP 服务器能够响应通过浏览器发起的自定义 HTTP 请求 在实际的 ABAP 集成项目中,这种方式非常使用。

    2024年03月21日
    浏览(33)
  • vue3使用axios发送post请求,后台接收到的参数总是null,使用postman测试后台是能接收数据的

    使用vue3,连基本的请求都失败了,使用浏览器查看post请求,参数中是有值,但是传到后台,每个参数都是null,不知道哪里错了。排除了后台的错误,就剩下了vue代码的错误了。我出错的地方是vue使用axios发送post请求的时候,参数格式写错了。 直接贴代码了,正确的写法 f

    2024年02月13日
    浏览(32)
  • STM32使用三种方式(阻塞、中断、DMA)实现串口发送和接收数据

    记录下学习STM32开发板的心得的和遇见的问题。 板卡型号:STM32F405RGT6 软件:STM32CubeMX、IAR STM32串口外设提供了3种接收和发送方式:阻塞、中断、DMA,主要给大家分享中断方式接收不定长数据和DMA使用空闲中断接收不定长数据。 阻塞发送: 阻塞接收: 两个函数需要注意的就

    2024年02月03日
    浏览(34)
  • C语言通过IXMLHTTPRequest以get或post方式发送http请求获取服务器文本或xml数据

    做过网页设计的人应该都知道ajax。 Ajax即Asynchronous Javascript And XML(异步的JavaScript和XML)。使用Ajax的最大优点,就是能在不更新整个页面的前提下维护数据。这使得Web应用程序更为迅捷地回应用户动作,并避免了在网络上发送那些没有改变的信息。 在IE浏览器中,Ajax技术就是

    2024年01月25日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包