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

image.png
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

阅读 9.2k
2 个回答

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题