java httpResponse调用getEntity()方法时注意事项

  • Post author:
  • Post category:java


项目中需要调用外部的接口,接口返回HttpResponse 对象,在取返回值里的内容的时候,犯了一个很隐蔽的问题!httpResponse.getEntity()不能调用多次,只能调用获取一次,存成一个临时的变量接收一下,在用这个临时变量进行后续的逻辑,如果不用变量接收的话,第二次再调用的时候取出来的对象就是null,导致后续处理报空指针异常!



错误示例:

//注意这个地方取了一次
log.info("responseStri:"+EntityUtils.toString(httpResponse.getEntity()));
//报空指针异常!坑就在这个地方,又获取的一次,httpResponse.getEntity()获取就是null,
String responseStr = (httpResponse.getEntity()).toString();
			



成功示例:

..............
..............
HttpResponse httpResponse = HttpRequestUtils.post(esbUrl,jsonParam,headerParam,httpParams);

		//post请求返回结果
		JSONObject jsonResult = null;
		//请求发送成功,并得到响应
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			String str = "";
			try {
				//读取服务器返回过来的json字符串数据
				str = EntityUtils.toString(httpResponse.getEntity());
				//把json字符串转换成json对象
				jsonResult = JSONObject.parseObject(str);
			} catch (Exception e) {
				log.error("post request submit error:" + esbUrl, e);
			}
		}else{
			try {
			String responseStr = (EntityUtils.toString(httpResponse.getEntity()));
			log.info("post request error:"+responseStr);
			jsonResult = JSONObject.parseObject(responseStr);
			log.info("FFFFFF:"+jsonResult.toString());
			} catch (Exception e) {
				log.error("post request submit error exception:" + esbUrl, e);
			}
		}



版权声明:本文为wujian_csdn_csdn原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。