一、commons-httpclient(3.1)(已经不在维护了)
<!--commons-httpclient(已经不在维护了)-->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.14</version>
</dependency>
commons-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");
//设置连接超时:
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;charset=gbk");
postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-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();
//########################################################//
//解决报警告的问题WARN : org.apache.commons.httpclient.HttpMethodBase -
//Going to buffer response body of large or unknown size.
//Using getResponseBodyAsStream instead is recommended.
InputStream is = postMethod.getResponseBodyAsStream();
//like12 modified,20220530,解决中文乱码的问题
//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;
}
二、httpclient(4.5.13)
<!--httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
httpclient调用示例
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;charset=utf-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)
List<NameValuePair> list = new ArrayList<NameValuePair>();
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, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//组织请求参数
if (null != params && !params.isEmpty()) {
StringBuilder stringBuilder = new StringBuilder(url);
stringBuilder.append("?");
for (Map.Entry<String, 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;charset=utf8");
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, Map<String,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.Entry<String, 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, Map<String,String> headers, Map<String,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.Entry<String, String> entry : headers.entrySet()) {
httpPost.setHeader(entry.getKey(),entry.getValue());
}
}
//组织请求参数
List<NameValuePair> paramList = new ArrayList <NameValuePair>();
if(params != null && params.size() > 0){
Set<String> 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, Map<String,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.Entry<String, 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, Map<String,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.Entry<String, 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, Map<String,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.Entry<String, 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>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.12</version>
</dependency>
hutool调用示例
/**
* hutoolGetBaseInfo
* @param sign
* @param apiCode
* @param accessToken
* @param data
* @return
*/
private static String hutoolGetBaseInfo(String sign, String apiCode, String accessToken, String data){
Map<String,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请求及文件上传 - 走看看