与httpclient(4.5.13) hutool(5.7.12))
一、commons-httpclient(3.1)(已经不在维护了)!--commons-httpclient(已经不在维护了)-- dependency groupIdcommons-httpclient/groupId artifactIdcommons-httpclient/artifactId version3.1/version /dependency dependency groupIdorg.apache.httpcomponents/groupId artifactIdhttpcore/artifactId version4.4.14/version /dependencycommons-httpclient调用示例import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.http.params.CoreConnectionPNames; private static final String paramBody {\param\: { \key\: \ key \,\secret\: \ secret \}}; /** * 获取token * param sign * return */ private static String getToken(String sign){ // 1.构造HttpClient的实例 HttpClient httpClient new HttpClient(); httpClient.getParams().setContentCharset(utf-8); // 设置超时时间【注意设置超时时间https时会报错无法正常使用PKIX path building failed】 httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000); // httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000); // 2.构造PostMethod的实例 PostMethod postMethod new PostMethod(url); // like12 add,20160511,中文转码 //在头文件中设置转码 // postMethod.addRequestHeader(Content-Type, application/x-www-form-urlencoded;charsetgbk); postMethod.addRequestHeader(Content-Type, application/json;charsetutf-8); // 3.0把参数放在Header中 postMethod.addRequestHeader(apiCode, apiCode); postMethod.addRequestHeader(appId,appId); postMethod.addRequestHeader(requestNo,requestNo); postMethod.addRequestHeader(sign,sign); // 3.把参数值放入到PostMethod对象中 // 方式1: // NameValuePair[] data { // new NameValuePair(param, ) // }; // postMethod.setRequestBody(data); // 方式2: postMethod.setRequestBody(paramBody); try { // 4.执行postMethod,调用http接口 httpClient.executeMethod(postMethod);//200 // 5.读取内容 // String responseMsg postMethod.getResponseBodyAsString().trim(); // ######################################################## // // 解决报警告的问题large or unknown size. Using getResponseBodyAsStream instead is recommended. InputStream is postMethod.getResponseBodyAsStream(); // 解决中文乱码的问题 // BufferedReader br new BufferedReader(new InputStreamReader(is)); BufferedReader br new BufferedReader(new InputStreamReader(is, UTF-8)); StringBuffer sb new StringBuffer(); String str ; while((str br.readLine()) ! null){ sb.append(str); } String responseMsg sb.toString(); // ######################################################## // System.out.println(responseMsg: responseMsg); // 6.处理返回的内容 return responseMsg; } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 7.释放连接 postMethod.releaseConnection(); } return null; }我的调用示例/** * postHttp * * return */ public String postHttp(String idCard){ // 解决https图片下载不了的问题 // Main函数中解决“Received fatal alert: protocol_version”报错 // 方案一增加启动变量 -Dhttps.protocolsTLSv1.2 // 方案二程序中添加代码 SSLContext context; try { context SSLContext.getInstance(TLSv1.2); context.init(null,null,null); SSLContext.setDefault(context); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // 1.构造HttpClient的实例 HttpClient httpClient new HttpClient(); httpClient.getParams().setContentCharset(utf-8); // 设置超时时间【注意设置超时时间https时会报错无法正常使用PKIX path building failed】 // httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000); // httpClient.getHttpConnectionManager().getParams().setSoTimeout(5000); // 2.构造PostMethod的实例 PostMethod postMethod new PostMethod(urlGlobal); // 中文转码在头文件中设置转码 postMethod.addRequestHeader(Content-Type, application/x-www-form-urlencoded;charsetutf-8); // 3.把参数值放入到PostMethod对象中 // 方式1: NameValuePair[] data { new NameValuePair(idCard, idCard) }; postMethod.setRequestBody(data); try { // 4.执行postMethod,调用http接口 httpClient.executeMethod(postMethod); // 5.读取内容 // String responseMsg postMethod.getResponseBodyAsString().trim(); // ######################################################## // // 解决报警告的问题large or unknown size. Using getResponseBodyAsStream instead is recommended. InputStream is postMethod.getResponseBodyAsStream(); // 解决中文乱码的问题 // BufferedReader br new BufferedReader(new InputStreamReader(is)); BufferedReader br new BufferedReader(new InputStreamReader(is, UTF-8)); StringBuffer sb new StringBuffer(); String str ; while((str br.readLine()) ! null){ sb.append(str); } String responseMsg sb.toString(); // ######################################################## // System.out.println(responseMsg: responseMsg); // 6.处理返回的内容 return responseMsg; } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 7.释放连接 postMethod.releaseConnection(); } return fail; }二、httpclient(4.5.13)!--httpclient-- dependency groupIdorg.apache.httpcomponents/groupId artifactIdhttpclient/artifactId version4.5.13/version /dependencyhttpclient调用示例import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; private static final String paramBody {\param\: { \key\: \ key \,\secret\: \ secret \}}; /** * 获取token * param sign * return */ private static String getToken(String sign){ CloseableHttpClient httpClient HttpClientBuilder.create().build(); HttpPost httpPost new HttpPost(url); //超时配置 RequestConfig config RequestConfig.custom() .setConnectTimeout(3000)//连接超时时间 .setConnectionRequestTimeout(3000)//连接请求超时时间 .setSocketTimeout(5000)//socket读写超时时间 .setCircularRedirectsAllowed(true)//设置是否允许重定向 默认为true .build(); httpPost.setConfig(config); //设置header httpPost.setHeader(Content-type, application/json;charsetutf-8); //把参数放在Header中 httpPost.setHeader(apiCode, apiCode); httpPost.setHeader(appId, appId); httpPost.setHeader(requestNo, requestNo); httpPost.setHeader(sign, sign); //组织请求参数 //方式一(直接String(raw时)) StringEntity entity new StringEntity(body, utf-8); httpPost.setEntity(entity); /*//方式二(拼接) String body accessToken accessToken data data; StringEntity entity new StringEntity(body, utf-8); httpPost.setEntity(entity);*/ /*//方式三(List) ListNameValuePair list new ArrayListNameValuePair(); list.add(new BasicNameValuePair(accessToken, accessToken)); list.add(new BasicNameValuePair(data, data)); UrlEncodedFormEntity entity null; try { entity new UrlEncodedFormEntity(list, utf-8); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } httpPost.setEntity(entity);*/ //执行 CloseableHttpResponse response null; try { response httpClient.execute(httpPost); return EntityUtils.toString(response.getEntity(), utf-8); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null ! response) { response.close(); } if (null ! httpClient) { httpClient.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; }HttpClientUtil.java工具类package com.qyj.utils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; public class HttpClientUtil { /** * httpclient 有参的get请求 * param url * param params * return */ public static String httpGet(String url, MapString, Object params) { CloseableHttpClient httpClient HttpClientBuilder.create().build(); //组织请求参数 if (null ! params !params.isEmpty()) { StringBuilder stringBuilder new StringBuilder(url); stringBuilder.append(?); for (Map.EntryString, Object entry : params.entrySet()) { stringBuilder.append(entry.getKey()).append() .append(entry.getValue()).append(); } url stringBuilder.toString(); } HttpGet httpGet new HttpGet(url); //超时配置 RequestConfig config RequestConfig.custom() .setConnectTimeout(3000)//连接超时时间 .setConnectionRequestTimeout(3000)//连接请求超时时间 .setSocketTimeout(5000)//socket读写超时时间 .setCircularRedirectsAllowed(true)//设置是否允许重定向 默认为true .build(); httpGet.setConfig(config); //执行 CloseableHttpResponse response null; try { response httpClient.execute(httpGet); return EntityUtils.toString(response.getEntity(), utf-8); } catch (IOException e) { e.printStackTrace(); } finally { try { if (response ! null) { response.close(); } if (httpClient ! null) { httpClient.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } /** * httpclient 对象参数的post请求 * param url * param jsonStr * return */ public static String httpPost(String url, String jsonStr) { CloseableHttpClient httpClient HttpClientBuilder.create().build(); HttpPost httpPost new HttpPost(url); //超时配置 RequestConfig config RequestConfig.custom() .setConnectTimeout(3000)//连接超时时间 .setConnectionRequestTimeout(3000)//连接请求超时时间 .setSocketTimeout(5000)//socket读写超时时间 .setCircularRedirectsAllowed(true)//设置是否允许重定向 默认为true .build(); httpPost.setConfig(config); //如果接受端是json形式必须指定Content-Type为json httpPost.setHeader(Content-Type, application/json;charsetutf8); StringEntity stringEntity new StringEntity(jsonStr, utf-8); httpPost.setEntity(stringEntity); //执行 CloseableHttpResponse response null; try { response httpClient.execute(httpPost); return EntityUtils.toString(response.getEntity(), utf-8); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null ! response) { response.close(); } if (null ! httpClient) { httpClient.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } //###################################################################// /** * 发送http get请求 * param url * param headers * return */ public static String httpGetHeader(String url, MapString,String headers){ CloseableHttpClient httpClient HttpClientBuilder.create().build(); HttpGet httpGet new HttpGet(url); //超时配置 RequestConfig config RequestConfig.custom() .setConnectTimeout(3000)//连接超时时间 .setConnectionRequestTimeout(3000)//连接请求超时时间 .setSocketTimeout(5000)//socket读写超时时间 .setCircularRedirectsAllowed(true)//设置是否允许重定向 默认为true .build(); httpGet.setConfig(config); //设置header if (headers ! null headers.size() 0) { for (Map.EntryString, String entry : headers.entrySet()) { httpGet.setHeader(entry.getKey(),entry.getValue()); } } //执行 CloseableHttpResponse response null; try { response httpClient.execute(httpGet); return EntityUtils.toString(response.getEntity(), utf-8); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null ! response) { response.close(); } if (null ! httpClient) { httpClient.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } /** * 发送http post请求参数以form表单键值对的形式提交 * param url * param headers * param params * return */ public static String httpPostParam(String url, MapString,String headers, MapString,String params){ CloseableHttpClient httpClient HttpClientBuilder.create().build(); HttpPost httpPost new HttpPost(url); //超时配置 RequestConfig config RequestConfig.custom() .setConnectTimeout(3000)//连接超时时间 .setConnectionRequestTimeout(3000)//连接请求超时时间 .setSocketTimeout(5000)//socket读写超时时间 .setCircularRedirectsAllowed(true)//设置是否允许重定向 默认为true .build(); httpPost.setConfig(config); //设置header if (headers ! null headers.size() 0) { for (Map.EntryString, String entry : headers.entrySet()) { httpPost.setHeader(entry.getKey(),entry.getValue()); } } //组织请求参数 ListNameValuePair paramList new ArrayList NameValuePair(); if(params ! null params.size() 0){ SetString keySet params.keySet(); for(String key : keySet) { paramList.add(new BasicNameValuePair(key, params.get(key))); } } try { httpPost.setEntity(new UrlEncodedFormEntity(paramList, utf-8)); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } //执行 CloseableHttpResponse response null; try { response httpClient.execute(httpPost); return EntityUtils.toString(response.getEntity(), utf-8); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null ! response) { response.close(); } if (null ! httpClient) { httpClient.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } /** * 发送http post请求参数以原生字符串进行提交 * param url * param headers * param jsonStr * return */ public static String httpPostRaw(String url, MapString,String headers, String jsonStr){ CloseableHttpClient httpClient HttpClientBuilder.create().build(); HttpPost httpPost new HttpPost(url); //超时配置 RequestConfig config RequestConfig.custom() .setConnectTimeout(3000)//连接超时时间 .setConnectionRequestTimeout(3000)//连接请求超时时间 .setSocketTimeout(5000)//socket读写超时时间 .setCircularRedirectsAllowed(true)//设置是否允许重定向 默认为true .build(); httpPost.setConfig(config); //设置header httpPost.setHeader(Content-type, application/json); if (headers ! null headers.size() 0) { for (Map.EntryString, String entry : headers.entrySet()) { httpPost.setHeader(entry.getKey(),entry.getValue()); } } //组织请求参数 StringEntity stringEntity new StringEntity(jsonStr, utf-8); httpPost.setEntity(stringEntity); //执行 CloseableHttpResponse response null; try { response httpClient.execute(httpPost); return EntityUtils.toString(response.getEntity(), utf-8); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null ! response) { response.close(); } if (null ! httpClient) { httpClient.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } /** * 发送http put请求参数以原生字符串进行提交 * param url * param headers * param jsonStr * return */ public static String httpPutRaw(String url, MapString,String headers, String jsonStr){ CloseableHttpClient httpClient HttpClientBuilder.create().build(); HttpPut httpPut new HttpPut(url); //超时配置 RequestConfig config RequestConfig.custom() .setConnectTimeout(3000)//连接超时时间 .setConnectionRequestTimeout(3000)//连接请求超时时间 .setSocketTimeout(5000)//socket读写超时时间 .setCircularRedirectsAllowed(true)//设置是否允许重定向 默认为true .build(); httpPut.setConfig(config); //设置header httpPut.setHeader(Content-type, application/json); if (headers ! null headers.size() 0) { for (Map.EntryString, String entry : headers.entrySet()) { httpPut.setHeader(entry.getKey(),entry.getValue()); } } //组织请求参数 StringEntity stringEntity new StringEntity(jsonStr, utf-8); httpPut.setEntity(stringEntity); //执行 CloseableHttpResponse response null; try { response httpClient.execute(httpPut); return EntityUtils.toString(response.getEntity(), utf-8); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null ! response) { response.close(); } if (null ! httpClient) { httpClient.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } /** * 发送http delete请求 * param url * param headers * return */ public static String httpDelete(String url, MapString,String headers){ CloseableHttpClient httpClient HttpClientBuilder.create().build(); HttpDelete httpDelete new HttpDelete(url); //超时配置 RequestConfig config RequestConfig.custom() .setConnectTimeout(3000)//连接超时时间 .setConnectionRequestTimeout(3000)//连接请求超时时间 .setSocketTimeout(5000)//socket读写超时时间 .setCircularRedirectsAllowed(true)//设置是否允许重定向 默认为true .build(); httpDelete.setConfig(config); //设置header if (headers ! null headers.size() 0) { for (Map.EntryString, String entry : headers.entrySet()) { httpDelete.setHeader(entry.getKey(),entry.getValue()); } } //执行 CloseableHttpResponse response null; try { response httpClient.execute(httpDelete); return EntityUtils.toString(response.getEntity(), utf-8); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null ! response) { response.close(); } if (null ! httpClient) { httpClient.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } //###################################################################// }三、hutool(5.7.12)!--hutool-- dependency groupIdcn.hutool/groupId artifactIdhutool-all/artifactId version5.7.12/version /dependencyhutool调用示例/** * hutoolGetBaseInfo * param sign * param apiCode * param accessToken * param data * return */ private static String hutoolGetBaseInfo(String sign, String apiCode, String accessToken, String data){ MapString,Object param new HashMap(); param.put(accessToken, accessToken); param.put(data, data); return HttpRequest.post(urlPostJsonForLangChaoXml) .header(apiCode, apiCode) .header(netType, 1) .header(requestNo, requestNo) .header(appId, appId) .header(sign, sign) .form(param)//表单内容 .timeout(3000)//超时毫秒 .execute().body(); }参考commons-httpclient与httpclient工具包 - 简书使用HttpClient 发送 GET、POST(FormData、Raw)、PUT、Delete请求及文件上传 - 走看看