工具类
package com.wei.com.api.sf.util;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
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.HttpGet;
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.HttpClients;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpUtils
{
private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
public static String sendGet(String url, String param)
{
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try
{
String urlNameString = url + "?" + param;
log.info("sendGet - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*
public static String sendPost(String url, String param)
{
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try
{
String urlNameString = url + "?" + param;
log.info("sendPost - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "**");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String ret = "";
while ((ret = br.readLine()) != null)
{
if (ret != null && !ret.trim().equals(""))
{
result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
}
}
log.info("recv - {}", result);
conn.disconnect();
br.close();
}
catch (ConnectException e)
{
log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
}
catch (SocketTimeoutException e)
{
log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
}
catch (IOException e)
{
log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
}
catch (Exception e)
{
log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
}
return result.toString();
}
private static class TrustAnyTrustManager implements X509TrustManager
{
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
{
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
{
}
@Override
public X509Certificate[] getAcceptedIssuers()
{
return new X509Certificate[] {};
}
}
private static class TrustAnyHostnameVerifier implements HostnameVerifier
{
@Override
public boolean verify(String hostname, SSLSession session)
{
return true;
}
}
public static String doPost(
String reqUrl, Map mapData, Map headerMap) {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
List formparams = new ArrayList();
if (mapData != null && !mapData.isEmpty()) {
for (Map.Entry entry : mapData.entrySet()) {
formparams.add(
new BasicNameValuePair(
entry.getKey(), entry.getValue() == null ? "" : entry.getValue().toString()));
}
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
log.info("post请求参数:" + formparams.toString());
HttpPost httpPost = new HttpPost(reqUrl);
httpPost.setEntity(entity);
// 设置请求头信息
if (headerMap != null && !headerMap.isEmpty()) {
for (Map.Entry entry : headerMap.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
// httpPostLog(httpPost);
log.info("httpPost.toString()=" + httpPost.toString());
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
StatusLine statusLine = httpResponse.getStatusLine();
int code = statusLine.getStatusCode();
String reasonPhrase = statusLine.getReasonPhrase();
log.info("响应状态码:" + code + ";原因或结果:" + reasonPhrase);
HttpEntity httpEntity = httpResponse.getEntity();
// System.out.println(new String(httpEntity.toString().getBytes("iso-8859-1"), "utf-8"));
return EntityUtils.toString(httpEntity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static Map getParamsByHeaderName(
HttpResponse response, String headerName) {
HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(headerName));
Map paramsMap = new HashMap();
while (it.hasNext()) {
HeaderElement elem = it.nextElement();
paramsMap.put(elem.getName(), elem.getValue());
}
return paramsMap;
}
public static String doGet(
String reqUrl, Map mapData, Map headerMap) {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet(reqUrl);
List formparams = new ArrayList();
if (mapData != null && !mapData.isEmpty()) {
for (Map.Entry entry : mapData.entrySet()) {
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
String params = EntityUtils.toString(entity);
log.info("Get请求参数:" + params);
System.out.println(httpGet.getURI().toString() + "?" + params);
httpGet.setURI(new URI(httpGet.getURI().toString() + "?" + params));
// 设置请求头信息
if (headerMap != null && !headerMap.isEmpty()) {
for (Map.Entry entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
}
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
StatusLine statusLine = httpResponse.getStatusLine();
int code = statusLine.getStatusCode();
String reasonPhrase = statusLine.getReasonPhrase();
log.info("响应状态码:" + code + ";原因或结果:" + reasonPhrase);
HttpEntity httpEntity = httpResponse.getEntity();
return EntityUtils.toString(httpEntity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
public static String doGet(
String reqUrl, Map headerMap) {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet(reqUrl);
List formparams = new ArrayList();
httpGet.setURI(new URI(httpGet.getURI().toString()));
// 设置请求头信息
if (headerMap != null && !headerMap.isEmpty()) {
for (Map.Entry entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
}
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
StatusLine statusLine = httpResponse.getStatusLine();
int code = statusLine.getStatusCode();
String reasonPhrase = statusLine.getReasonPhrase();
log.info("响应状态码:" + code + ";原因或结果:" + reasonPhrase);
HttpEntity httpEntity = httpResponse.getEntity();
return EntityUtils.toString(httpEntity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
public static String doPostMapJson(
String reqUrl, Map mapData, Map headerMap) {
JSONObject jsonParams = new JSONObject();
if (mapData != null) {
for (Map.Entry entry : mapData.entrySet()) {
try {
jsonParams.put(entry.getKey(), entry.getValue());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return doPostJson(reqUrl, jsonParams, headerMap);
}
public static String doPostJson(
String reqUrl, JSONObject jsonParams, Map headerMap) {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
log.info("post请求数据:" + jsonParams.toString());
StringEntity entity = new StringEntity(jsonParams.toString(), "UTF-8"); // 解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
HttpPost httpPost = new HttpPost(reqUrl);
//httpPost.setConfig(setTimeOutConfig(httpPost.getConfig(),10));
httpPost.setEntity(entity);
// 设置请求头信息
if (headerMap != null && !headerMap.isEmpty()) {
for (Map.Entry entry : headerMap.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
// httpPostLog(httpPost);
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
StatusLine statusLine = httpResponse.getStatusLine();
int code = statusLine.getStatusCode();
String reasonPhrase = statusLine.getReasonPhrase();
log.info("响应状态码:" + code + ";原因或结果:" + reasonPhrase);
HttpEntity httpEntity = httpResponse.getEntity();
System.out.println("Encoding:"+httpEntity.getContentEncoding());
System.out.println("ContentType:"+httpEntity.getContentType());
return EntityUtils.toString(httpEntity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String doPostJson(
String reqUrl, String reqXml, Map headerMap) {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
log.info("post请求数据:" + reqXml.toString());
StringEntity entity = new StringEntity(reqXml.toString(), "UTF-8"); // 解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
HttpPost httpPost = new HttpPost(reqUrl);
httpPost.setEntity(entity);
// 设置请求头信息
if (headerMap != null && !headerMap.isEmpty()) {
for (Map.Entry entry : headerMap.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
// httpPostLog(httpPost);
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
StatusLine statusLine = httpResponse.getStatusLine();
int code = statusLine.getStatusCode();
String reasonPhrase = statusLine.getReasonPhrase();
log.info("响应状态码:" + code + ";原因或结果:" + reasonPhrase);
HttpEntity httpEntity = httpResponse.getEntity();
System.out.println("Encoding:"+httpEntity.getContentEncoding());
System.out.println("ContentType:"+httpEntity.getContentType());
return EntityUtils.toString(httpEntity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void httpPostLog(HttpPost httpPost) {
try {
System.out.println("httpPostLog begin===");
// log.info("httpPostLog begin");
System.out.println(httpPost.getRequestLine());
// log.info(httpPost.getRequestLine().toString());
Header[] headers = httpPost.getAllHeaders();
// log.info("Cookie:");
for (Header header : headers) {
String k = header.getName();
String v = header.getValue();
System.out.println(k + "=" + v);
// log.info(k + "=" + v);
}
String contentType = httpPost.getEntity().getContentType().getValue();
System.out.println("Content-Type:" + contentType);
// log.info("Content-Type:" + contentType);
int length = (int) httpPost.getEntity().getContentLength();
byte[] bytes = new byte[length];
httpPost.getEntity().getContent().read(bytes);
System.out.println("Content:" + URLDecoder.decode(new String(bytes), "UTF-8"));
// log.info("Content:" + new String(bytes));
System.out.println("httpPostLog end===");
} catch (Exception ex) {
log.info("httpPostLog Exception");
}
}
private static RequestConfig setTimeOutConfig(RequestConfig requestConfig,int seconds){
if(requestConfig == null) {
requestConfig = RequestConfig.custom().build();
}
return RequestConfig.copy(requestConfig)
.setConnectionRequestTimeout(seconds*1000)
.setConnectTimeout(seconds*1000)
.setSocketTimeout(seconds*1000)
.build();
}
private static String TruncateUrlPage(String strURL){
String strAllParam=null;
String[] arrSplit=null;
strURL=strURL.trim().toLowerCase();
arrSplit=strURL.split("[?]");
if(strURL.length()>1){
if(arrSplit.length>1){
for (int i=1;i urlSplit(String URL){
Map mapRequest = new HashMap();
String[] arrSplit=null;
String strUrlParam=TruncateUrlPage(URL);
if(strUrlParam==null){
return mapRequest;
}
arrSplit=strUrlParam.split("[&]");
for(String strSplit:arrSplit){
String[] arrSplitEqual=null;
arrSplitEqual= strSplit.split("[=]");
//解析出键值
if(arrSplitEqual.length>1){
//正确解析
mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
}else{
if(arrSplitEqual[0]!=""){
//只有参数没有值,不加入
mapRequest.put(arrSplitEqual[0], "");
}
}
}
return mapRequest;
}
public static void main(String[] args) {
}
}



