使用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;
    }
	
}

你可能感兴趣的:(java)