文章目录
调用远程链接工具类
在调用远程连接时需要通过 CloseableHttpClient 和 HttpPost/HttpGet/HttpPut 等创建访问远程链接的http, 以HttpPost为例:
其中 CloseableHttpClient 的创建方式有两种, 一种是下方使用的, 另一种是
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
发送请求: CloseableHttpResponse response = closeableHttpClient.execute(httpPost)
public class HttpUtil {
public static String doPost(String url, List pairList){
CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
HttpPost httpPost =new HttpPost(url);
String responseString ="";
try {
httpPost.setEntity(new UrlEncodedFormEntity(pairList));
try(CloseableHttpResponse response = closeableHttpClient.execute(httpPost)) {
responseString = EntityUtils.toString(response.getEntity());
}
}catch (IOException e) {
e.printStackTrace();
}
return responseString;
}
public static String doPostWithJSON(String url, JSONObject jsonObject){
CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
HttpPost httpPost =new HttpPost(url.trim());
httpPost.addHeader("Content-Type","application/json;charset=UTF-8");
String responseString ="";
StringEntity stringEntity =new StringEntity(jsonObject.toString(), "UTF-8");
stringEntity.setContentEncoding("UTF-8");
httpPost.setEntity(stringEntity);
try(CloseableHttpResponse response = closeableHttpClient.execute(httpPost);) {
responseString = EntityUtils.toString(response.getEntity());
}catch (IOException e) {
e.printStackTrace();
}
return responseString;
}
}
访问远程链接时遇到的问题
Attempted read from closed stream
在同一个httpclient中只能有一个获取entity的方法, 报这个错应该时多写了一个, 去掉其中一个即可
check your viewResolver setUp
在springboot中出现该报错一般是没有加@ResponseBody注解
ClientProtoclExceotion: target host is not specified
没有请求头, 可能时url链接的地址不对, 没有把http://识别出来, 我遇到这个问题是因为把整个url做了字符编码utf-8 , 所以:和//都被转义了, 导致最后在发送请求的时候没有把http头识别出来