开发者社区> 问答> 正文

java调用第三方接口,获取接口返回的数据。 报错

"

<span class=""img-wrap""><img referrerpolicy=""no-referrer"" data-src=""/img/bVbDgeR"" src=""https://cdn.segmentfault.com/v-5e8d8dec/global/img/squares.svg"" alt=""image.png"" title=""image.png"" />
java接收远程调用的数据,得到的是如上个数的返回内容,我怎么写才能获取到值,现在使用的请求方法如下:

<code class=""java"">public static HttpResult postJsonData(String url, Map<String,String> params, String charset) throws Exception{
CloseableHttpClient httpclient = HttpClientUtil.createDefault();
HttpPost httpPost = new HttpPost(url);
//拼接参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
String key = entry.getKey().toString();
String value = entry.getValue().toString();
System.out.println("key=" + key + " value=" + value);
NameValuePair pair = new BasicNameValuePair(key, value);
list.add(pair);
}
CloseableHttpResponse response=null;
try {
if(StringUtils.isEmpty(charset)){
charset = DEFAULT_CHARSET;
}
httpPost.setEntity(new UrlEncodedFormEntity(list,charset));
response = httpclient.execute(httpPost);
/**请求发送成功,并得到响应**/
if(response!=null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity httpEntity = response.getEntity();
if (httpEntity!=null){
System.out.println("响应内容为:" + EntityUtils.toString(httpEntity));
//System.out.println("响应内容为1:" + httpEntity.getContent());
}
String result=null;
try {
result = EntityUtils.toString(httpEntity,DEFAULT_CHARSET);
logger.info(result);
} catch (IOException e) {
throw e;
} finally {
EntityUtils.consume(httpEntity);
}
return JSON.parseObject(result,HttpResult.class);
//return httpEntity.getContent();
}else{
return null;
}
} catch (IOException e) {
throw new Exception(e.getMessage());
}finally {
try{
// 释放资源
if(response!=null){
response.close();
}
if(httpclient!=null){
httpclient.close();
}
}catch (IOException e1){
throw new Exception("CloseableHttpResponse close exception");
}

}  

}

求教怎么写才能把返回的值取到,现在用上边的方法会报如下错误:

" ![image.png](https://ucc.alicdn.com/pic/developer-ecology/ca58ff66ee92423b92c2d803210c50b4.png)

展开
收起
因为相信,所以看见。 2020-05-26 13:56:40 1568 0
1 条回答
写回答
取消 提交回答
  • 阿里,我所有的向往

    httpEntity 只能读取一次的,当调用这个指挥 EntityUtils.toString(httpEntity),就被关闭了。这个只用一次,你看下还报错不

    ![image.png](https://ucc.alicdn.com/pic/developer-ecology/c8a36a57916c444ca6ff6c26d750ce62.png)
    2020-05-27 10:07:52
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载