get 请求
public String get(String url ,String token){
CloseableHttpClient httpClient = null;
HttpGet httpGet = null;
String result="";
try {
httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
httpGet = new HttpGet(url);
httpGet .setHeader("token", token);
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity httpEntity = response.getEntity();
result = EntityUtils.toString(httpEntity, "utf-8");
//释放所有由httpEntity所持有的资源
EntityUtils.consume(httpEntity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
post 请求 json格式的转化成string传入
public String post(String url,String json){
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
String result = "";
try {
httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
// 设置请求格式
httpPost.setHeader("Content-type","application/json");
// 给httppost对象设置json格式的参数
StringEntity httpEntity = new StringEntity(json,"utf-8");
// 传参
httpPost.setEntity(httpEntity);
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity httpEntity2 = response.getEntity();
result = EntityUtils.toString(httpEntity2, "utf-8");
EntityUtils.consume(httpEntity2);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}