直接贴码
import java.io.*;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;
/**
*
* 自定义HTTP请求工具类(HttpClient)
*
*/
@Log4j2
public class HttpClientUtil {
/**
* 发起POST请求
* @param url
* @param params
* @return
*/
public static String post(String url, Map<String, String> params) {
//创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
String body = null;
try {
log.info("create httppost:" + url);
HttpPost post = postForm(url, params);
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(post);
try {
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, "UTF-8");
}
EntityUtils.consume(entity);
}finally {
//释放链接
response.close();
}
}catch (IOException e) {
throw new RuntimeSystemException(e);
}finally{
try{
closeHttpClient(client);
} catch(Exception e){
throw new RuntimeSystemException(e);
}
}
return body;
}
/**
* 发送GET请求
*
* @param url
* @return
*/
public static String get(String url) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
String body = null;
try {
log.info("create httppost:" + url);
HttpGet get = new HttpGet(url);
CloseableHttpResponse httpResponse = null;
//发送get请求
httpResponse = httpClient.execute(get);
try {
//response实体
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, "UTF-8");
}
} finally {
httpResponse.close();
}
}catch (Exception e){
throw new RuntimeSystemException(e);
}finally{
try{
closeHttpClient(httpClient);
} catch (IOException e){
throw new RuntimeSystemException(e);
}
}
return body;
}
/**
* 关闭请求
* @param client
* @throws IOException
*/
public static void closeHttpClient(CloseableHttpClient client) throws IOException{
if (client != null){
client.close();
}
}
/**
* HTTP POST 提交 JSON数据
*
* @param url
* @param json json字符串
* @throws Exception
*/
public static String httpPostWithJSON(String url, String json) throws Exception {
// 将JSON进行UTF-8编码,以便传输中文
String encoderJson = URLEncoder.encode(json, "UTF-8");
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
StringEntity se = new StringEntity(encoderJson);
se.setContentType("text/json");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);
CloseableHttpResponse response = httpClient.execute(httpPost);
// 返回数据
String body = paseResponse(response);
closeHttpClient(httpClient);
return body;
}
/**
* HTTP POST 提交 XML数据
*
* @param url
* @param xml xml字符串
* @return
* @throws Exception
*/
public static String httpPostWithXML(String url, String xml) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
Integer statusCode = -1;
HttpPost post = new HttpPost(url);
StringEntity entity = new StringEntity(xml);
post.setEntity(entity);
post.setHeader(HTTP.CONTENT_TYPE, "text/xml;charset=UTF-8");
HttpResponse response = httpClient.execute(post);
// 返回数据
String body = paseResponse(response);
httpClient.getConnectionManager().shutdown();
return body;
}
/**
* 发起Https请求
*
* @param requestUrl
* @param requestMethod
* @param outputStr
* @return
*/
public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
// 当outputStr不为null时向输出流写数据
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 从输入流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
return buffer.toString();
} catch (ConnectException ce) {
log.error("连接超时:{}", ce);
throw new RuntimeSystemException(ce);
} catch (Exception e) {
log.error("https请求异常:{}", e);
throw new RuntimeSystemException(e);
}
}
/**
* 返回Response
* @param response
* @return
*/
private static String paseResponse(HttpResponse response) {
log.info("get response from http server..");
HttpEntity entity = response.getEntity();
log.info("response status: " + response.getStatusLine());
String charset = "UTF-8";
String body = null;
try {
charset = getContentCharSet(entity);
log.info(charset);
body = EntityUtils.toString(entity,charset);
log.info(body);
} catch (Exception e) {
log.error("parseResponse error:"+e.getMessage());
throw new RuntimeSystemException(e);
}
return body;
}
/**
* 默认编码utf -8
*
* @param entity
* @return
* @throws ParseException
*/
public static String getContentCharSet(final HttpEntity entity)
throws ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
String charset = null;
if (entity.getContentType() != null) {
HeaderElement values[] = entity.getContentType().getElements();
if (values.length > 0) {
NameValuePair param = values[0].getParameterByName("charset" );
if (param != null) {
charset = param.getValue();
}
}
}
if(StringUtils.isEmpty(charset)){
charset = "UTF-8";
}
return charset;
}
/**
* 发起请求
* @param httpclient
* @param httpost
* @return
*/
private static HttpResponse sendRequest(DefaultHttpClient httpclient,
HttpUriRequest httpost) {
log.info("execute post...");
HttpResponse response = null;
try {
response = httpclient.execute(httpost);
} catch (Exception e) {
log.error("sendRequest error:"+e.getMessage());
throw new RuntimeSystemException(e);
}
return response;
}
/**
* 生成POST
* @param url
* @param params
* @return
*/
private static HttpPost postForm(String url, Map<String, String> params){
HttpPost httpost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList <NameValuePair>();
// 整理参数
Set<String> keySet = params.keySet();
for(String key : keySet) {
nvps.add(new BasicNameValuePair(key, params.get(key)));
}
try {
log.info("set utf-8 form entity to httppost");
httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
} catch (UnsupportedEncodingException e) {
log.error("postForm error:"+e.getMessage());
throw new RuntimeSystemException(e);
}
return httpost;
}
}
httpclient4.5.2.jar