import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import com.gjw.common.exception.BEException;
import tk.mybatis.mapper.util.StringUtil;
/**
* http请求工具类
*/
public class HttpUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
private static int SocketTimeout = 3000;//3秒
private static int ConnectTimeout = 3000;//3秒
private static Boolean SetTimeOut = true;
/**
* 获取ip地址
* @param request
* @return
*/
public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("proxy_add_x_forwarded_for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("x-forwarded-for");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
// /**
// * 判断是否是ajax请求
// * @param request
// * @return
// */
// public static boolean isAjax(HttpServletRequest request){
// return (request.getHeader("X-Requested-With") != null
// && "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString())) ;
// }
// /**
// * 判断是否是ajax请求
// * @param webRequest
// * @return
// */
// public static boolean isAjaxRequest(WebRequest webRequest) {
// String requestedWith = webRequest.getHeader("X-Requested-With");
// return requestedWith != null ? "XMLHttpRequest".equals(requestedWith) : false;
// }
private static CloseableHttpClient getHttpClient() {
RegistryBuilder registryBuilder = RegistryBuilder.create();
ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory();
registryBuilder.register("http", plainSF);
//指定信任密钥存储对象和连接套接字工厂
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
//信任任何链接
TrustStrategy anyTrustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
};
SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build();
LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
registryBuilder.register("https", sslSF);
} catch (KeyStoreException e) {
logger.error(e.getMessage(),e);
throw new RuntimeException(e);
} catch (KeyManagementException e) {
logger.error(e.getMessage(),e);
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
logger.error(e.getMessage(),e);
throw new RuntimeException(e);
}
Registry registry = registryBuilder.build();
//设置连接管理器
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
// connManager.setDefaultConnectionConfig(connConfig);
// connManager.setDefaultSocketConfig(socketConfig);
//构建客户端
return HttpClientBuilder.create().setConnectionManager(connManager).build();
}
/**
* get
*
* @param url 请求的url
* @param queries 请求的参数,在浏览器?后面的数据,没有可以传null
* @return
* @throws IOException
*/
public static String get(String url, Map queries) {
String responseBody = "";
//CloseableHttpClient httpClient=HttpClients.createDefault();
//支持https
CloseableHttpClient httpClient = getHttpClient();
StringBuilder sb = new StringBuilder(url);
if (queries != null && queries.keySet().size() > 0) {
boolean firstFlag = true;
Iterator iterator = queries.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
if (firstFlag) {
sb.append("?" + (String) entry.getKey() + "=" + (String) entry.getValue());
firstFlag = false;
} else {
sb.append("&" + (String) entry.getKey() + "=" + (String) entry.getValue());
}
}
}
HttpGet httpGet = new HttpGet(sb.toString());
if (SetTimeOut) {
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(SocketTimeout)
.setConnectTimeout(ConnectTimeout).build();//设置请求和传输超时时间
httpGet.setConfig(requestConfig);
}
try {
logger.info("Executing request " + httpGet.getRequestLine());
//请求数据
CloseableHttpResponse response = httpClient.execute(httpGet);
System.out.println(response.getStatusLine());
int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
responseBody = EntityUtils.toString(entity,"UTF-8");
//EntityUtils.consume(entity);
} else {
logger.error("http return status error:" + status);
throw new ClientProtocolException("Unexpected response status: " + status);
}
} catch (Exception ex) {
ex.printStackTrace();
logger.error(ex.getMessage(),ex);
} finally {
try {
httpClient.close();
} catch (IOException e) {
logger.error(e.getMessage(),e);
}
}
return responseBody;
}
/**
* 返回InputStream 外部请注意关闭
* @param url
* @param queries
* @return
*/
public static byte[] getStream(String url, Map queries) {
//支持https
CloseableHttpClient httpClient = getHttpClient();
InputStream inputStream = null ;
StringBuilder sb = new StringBuilder(url);
if (queries != null && queries.keySet().size() > 0) {
boolean firstFlag = true;
Iterator iterator = queries.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
if (firstFlag) {
sb.append("?" + (String) entry.getKey() + "=" + (String) entry.getValue());
firstFlag = false;
} else {
sb.append("&" + (String) entry.getKey() + "=" + (String) entry.getValue());
}
}
}
HttpGet httpGet = new HttpGet(sb.toString());
if (SetTimeOut) {
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(SocketTimeout)
.setConnectTimeout(ConnectTimeout).build();//设置请求和传输超时时间
httpGet.setConfig(requestConfig);
}
try {
System.out.println("Executing request " + httpGet.getRequestLine());
//请求数据
CloseableHttpResponse response = httpClient.execute(httpGet);
System.out.println(response.getStatusLine());
int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
int count = 0;
while (count == 0) {
count = Integer.parseInt(""+entity.getContentLength());//in.available();
}
byte[] bytes = new byte[count];
int readCount = 0; // 已经成功读取的字节的个数
while (readCount <= count) {
if(readCount == count)break;
readCount += inputStream.read(bytes, readCount, count - readCount);
}
inputStream.close();
return bytes;
} else {
System.out.println("http return status error:" + status);
throw new ClientProtocolException("Unexpected response status: " + status);
}
} catch (Exception ex) {
ex.printStackTrace();
logger.error(ex.getMessage(),ex);
} finally {
try {
httpClient.close();
} catch (IOException e) {
logger.error(e.getMessage(),e);
}
}
return new byte[0];
}
/**
* post
*
* @param url 请求的url
* @param queries 请求的参数,在浏览器?后面的数据,没有可以传null
* @param params post form 提交的参数
* @return
* @throws IOException
*/
public static String post(String url, Map queries, Map params) {
String responseBody = "";
//CloseableHttpClient httpClient = HttpClients.createDefault();
//支持https
CloseableHttpClient httpClient = getHttpClient();
StringBuilder sb = new StringBuilder(url);
if (queries != null && queries.keySet().size() > 0) {
boolean firstFlag = true;
Iterator iterator = queries.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
if (firstFlag) {
sb.append("?" + (String) entry.getKey() + "=" + (String) entry.getValue());
firstFlag = false;
} else {
sb.append("&" + (String) entry.getKey() + "=" + (String) entry.getValue());
}
}
}
//指定url,和http方式
HttpPost httpPost = new HttpPost(sb.toString());
if (SetTimeOut) {
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(SocketTimeout)
.setConnectTimeout(ConnectTimeout).build();//设置请求和传输超时时间
httpPost.setConfig(requestConfig);
}
//添加参数
List nvps = new ArrayList();
if (params != null && params.keySet().size() > 0) {
Iterator> iterator = params.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
nvps.add(new BasicNameValuePair((String) entry.getKey(), (String) entry.getValue()));
}
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
//请求数据
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
logger.error(e.getMessage(),e);
}
try {
System.out.println(response.getStatusLine());
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
responseBody = EntityUtils.toString(entity,"UTF-8");
//EntityUtils.consume(entity);
} else {
System.out.println("http return status error:" + response.getStatusLine().getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
logger.error(e.getMessage(),e);
}
}
return responseBody;
}
/**
* 计算工作日
* start="2017-09-28" 只接收这种格式,其他格式不接收
* @author: gaog
* @date: 2017年10月10日 下午2:30:20
*/
public static Integer getWorkDay(Date startTime, Date endTime){
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.fynas.com/workday/count");
List pairs = new ArrayList();
pairs.add(new BasicNameValuePair("start_date", DateUtil.formatYYYYMMDD(startTime)));
pairs.add(new BasicNameValuePair("end_date", DateUtil.formatYYYYMMDD(endTime)));
UrlEncodedFormEntity entity = null;
try {
entity = new UrlEncodedFormEntity(pairs, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw BEException.me("组装请求数据失败!");
}
httppost.setEntity(entity);
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
httppost.setConfig(requestConfig);
CloseableHttpResponse responseBody = null;
String ret = "";
try {
responseBody = httpclient.execute(httppost);
ret = EntityUtils.toString(responseBody.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
throw BEException.me("调用接口失败!");
} catch (IOException e) {
throw BEException.me("调用接口失败!");
} finally {
try {
if (null != responseBody) {
responseBody.close();
}
} catch (IOException e) {
throw BEException.me("调用接口失败!");
}
try {
httpclient.close();
} catch (IOException e) {
throw BEException.me("调用接口失败!");
}
}
if (StringUtil.isEmpty(ret)) {
throw BEException.me("调用接口失败!");
}
if("0".equals(JSONObject.parseObject(ret).getString("status"))){
System.out.println("workday="+JSONObject.parseObject(JSONObject.parseObject(ret).getString("data")).getString("workday"));
String workday = JSONObject.parseObject(JSONObject.parseObject(ret).getString("data")).getString("workday");
return Integer.valueOf(workday);
}else{
throw BEException.me("调用接口失败!");
}
}
/**
* start="2017-09-28" 只接收这种格式,其他格式不接收
* @author: gaog
* @date: 2017年10月10日 下午2:57:32
*/
public static Date getWorkEnd(Date startTime, int days){
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.fynas.com/workday/end");
List pairs = new ArrayList();
pairs.add(new BasicNameValuePair("start_date", DateUtil.formatYYYYMMDD(startTime)));
pairs.add(new BasicNameValuePair("days", days+""));
UrlEncodedFormEntity entity = null;
try {
entity = new UrlEncodedFormEntity(pairs, "UTF-8");
} catch (UnsupportedEncodingException e) {
System.out.println("http return status error:" + e.getMessage());
throw BEException.me("组装请求数据失败!");
}
httppost.setEntity(entity);
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
httppost.setConfig(requestConfig);
CloseableHttpResponse responseBody = null;
String ret = "";
try {
responseBody = httpclient.execute(httppost);
ret = EntityUtils.toString(responseBody.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
System.out.println("http return status error:" + e.getMessage());
throw BEException.me("调用接口失败!");
} catch (IOException e) {
System.out.println("http return status error:" + e.getMessage());
throw BEException.me("调用接口失败!");
} finally {
try {
if (null != responseBody) {
responseBody.close();
}
} catch (IOException e) {
System.out.println("http return status error:" + e.getMessage());
throw BEException.me("调用接口失败!");
}
try {
httpclient.close();
} catch (IOException e) {
System.out.println("http return status error:" + e.getMessage());
throw BEException.me("调用接口失败!");
}
}
if (StringUtil.isEmpty(ret)) {
throw BEException.me("调用接口失败!");
}
if("0".equals(JSONObject.parseObject(ret).getString("status"))){
System.out.println("workend="+JSONObject.parseObject(ret).getString("data"));
return DateUtil.parse(JSONObject.parseObject(ret).getString("data"), "yyyy-MM-dd");
}else{
System.out.println("http return status error:" + ret);
throw BEException.me("调用接口失败!");
}
}
}