使用HttpClient访问springboot项目接口返回JSON并获取指定key的value值

发送带json数据的请求,获取响应,并通过key=result,key=name获取响应正文多层json格式数据中name对应的value
HttpClient发送post请求过程
1.创建httpclient实例
2.设置请求的url路径
3.创建httppost实例
4.设置entity字符串数据
5.通过httpclient.execute()方法发送请求,并返回httpsponse对象。
6.解析httpresponse对象,关闭httpclient.

		String result = null;
		CloseableHttpClient ch = HttpClientBuilder.create().build();
		String url = "YOURIP";
		HttpPost post = new HttpPost(url);
		try {
		JSONObject json = new JSONObject();
		json.put("id", "1");
		json.put("name", "myself");
		json.put("age","20");
		System.err.println(json);
		StringEntity s = new StringEntity(json.toString());	
		//设置编码方式
		s.setContentEncoding("utf-8");
		//设置发送数据格式
		s.setContentType("application/json");
		post.setEntity(s);
		//获取响应
		HttpResponse response = ch.execute(post);
		if(response.getStatusLine().getStatusCode() == 200) {
			String str = response.getEntity().toString();
			System.err.println(str);
			result = "请求成功";
			获取响应正文
			String conResult = EntityUtils.toString(response.getEntity());
			System.out.println(conResult);
			//转换成map,不知道什么原因,conResult无法通过JSONObject.praseObject("conResult")方法转换成JSON对象。
			//JSONObject json1 = JSONObject.parseObject(conResult);
			Map<String,JSONObject> map1 = (Map)JSON.parse(conResult); 
			//通过key=result,key=name,获取name对应的value值 
			JSONObject json2 = map1.get("result");
			System.err.println(json2.get("name"));
		}else {
			int err = response.getStatusLine().getStatusCode();
			result = "发送失败,响应码:"+err;
		}
		} catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
        	try {
				ch.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }

具体的接口

@RestController
@RequestMapping("/connectDemo")
public class demoApi {
	
	@RequestMapping("/get")
	public JSONObject addUser(@RequestBody JSONObject userEntity)
    {
        System.out.println(JSONObject.toJSONString(userEntity));
        JSONObject json=new JSONObject();
        json.fluentPut("result",userEntity);
        return json;
    }
	
}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值