package com.gk.hotwork.Domain.Utils;
|
|
import org.apache.http.Header;
|
import org.apache.http.HttpStatus;
|
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.ContentType;
|
import org.apache.http.entity.StringEntity;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.HttpClients;
|
import org.apache.http.util.EntityUtils;
|
import org.apache.log4j.LogManager;
|
import org.apache.log4j.Logger;
|
|
import java.io.*;
|
import java.net.HttpURLConnection;
|
import java.net.URL;
|
import java.net.URLEncoder;
|
import java.util.Map;
|
|
public class HttpUtils {
|
private static final Logger logger = LogManager.getLogger(HttpUtils.class);
|
|
public static final String DEF_CHATSET = "UTF-8";
|
public static final int DEF_CONN_TIMEOUT = 30000;
|
public static final int DEF_READ_TIMEOUT = 30000;
|
public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29";
|
/**
|
*
|
* @param strUrl 请求地址
|
* @param params 请求参数
|
* @param method 请求方法
|
* @return 网络请求字符串
|
* @throws Exception
|
*/
|
public static String net(String strUrl, Map params, String method) throws Exception {
|
HttpURLConnection conn = null;
|
BufferedReader reader = null;
|
String rs = null;
|
try {
|
StringBuffer sb = new StringBuffer();
|
if(method==null || method.equals("GET")){
|
strUrl = strUrl+"?"+urlencode(params);
|
}
|
URL url = new URL(strUrl);
|
conn = (HttpURLConnection) url.openConnection();
|
if(method==null || method.equals("GET")){
|
conn.setRequestMethod("GET");
|
}else{
|
conn.setRequestMethod("POST");
|
conn.setDoOutput(true);
|
}
|
conn.setRequestProperty("User-agent", userAgent);
|
conn.setUseCaches(false);
|
conn.setConnectTimeout(DEF_CONN_TIMEOUT);
|
conn.setReadTimeout(DEF_READ_TIMEOUT);
|
conn.setInstanceFollowRedirects(false);
|
conn.connect();
|
if (params!= null && method.equals("POST")) {
|
try {
|
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
|
out.writeBytes(urlencode(params));
|
} catch (Exception e) {
|
// TODO: handle exception
|
}
|
}
|
InputStream is = conn.getInputStream();
|
reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
|
String strRead = null;
|
while ((strRead = reader.readLine()) != null) {
|
sb.append(strRead);
|
}
|
rs = sb.toString();
|
} catch (IOException e) {
|
e.printStackTrace();
|
} finally {
|
if (reader != null) {
|
reader.close();
|
}
|
if (conn != null) {
|
conn.disconnect();
|
}
|
}
|
return rs;
|
}
|
|
//将map型转为请求参数型
|
public static String urlencode(Map<String,Object>data) {
|
StringBuilder sb = new StringBuilder();
|
for (Map.Entry i : data.entrySet()) {
|
try {
|
sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
|
} catch (UnsupportedEncodingException e) {
|
e.printStackTrace();
|
}
|
}
|
return sb.toString();
|
}
|
|
//post json
|
// public static String sendPost(String url, String data) {
|
// String response = null;
|
// try {
|
// HttpClient httpclient = null;
|
// HttpResponse httpresponse = null;
|
// HttpPost httppost = null;
|
//
|
// try {
|
// httpclient = HttpClients.createDefault();
|
// httppost = new HttpPost(url);
|
// StringEntity stringentity = new StringEntity(data,
|
// ContentType.create("application/json", "UTF-8"));
|
// httppost.setEntity(stringentity);
|
// httpresponse = httpclient.execute(httppost);
|
// response = EntityUtils
|
// .toString(httpresponse.getEntity());
|
// // 检验返回码
|
// int statusCode = httpresponse.getStatusLine().getStatusCode();
|
// if(statusCode != HttpStatus.SC_OK){
|
// logger.error("请求出错: "+statusCode);
|
// if (statusCode == 307) {
|
// Header header = httpresponse.getFirstHeader("location"); // 跳转的目标地址是在 HTTP-HEAD上
|
// String newuri = header.getValue(); // 这就是跳转后的地址,再向这个地址发出新申请
|
// logger.error(newuri);
|
//
|
// httppost = new HttpPost(newuri);
|
// StringEntity newstringentity = new StringEntity(data,
|
// ContentType.create("application/json", "UTF-8"));
|
// httppost.setEntity(newstringentity);
|
// httpresponse = httpclient.execute(httppost);
|
// response = EntityUtils
|
// .toString(httpresponse.getEntity());
|
//
|
// logger.error("请求出错: "+httpresponse.getStatusLine().getStatusCode());
|
// }
|
//
|
// }
|
// } catch (Exception e){
|
// e.printStackTrace();
|
// }finally {
|
// if(httppost != null){
|
// try {
|
// httppost.releaseConnection();
|
// Thread.sleep(500);
|
// } catch (InterruptedException e) {
|
// e.printStackTrace();
|
// }
|
// }
|
// }
|
// } catch (Exception e) {
|
// e.printStackTrace();
|
// }
|
// return response;
|
// }
|
|
public static String sendPost(String url, String data) {
|
String resData = null;
|
try {
|
RequestConfig config = RequestConfig.custom().setRedirectsEnabled(false).build();//不允许重定向
|
CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();
|
|
// CloseableHttpClient client = HttpClients.createDefault();
|
HttpPost post = new HttpPost(url);
|
post.setHeader("Content-Type", "application/json;charset=UTF-8");
|
StringEntity se = new StringEntity(data, "UTF-8");
|
se.setContentEncoding("UTF-8");
|
se.setContentType("application/json");
|
post.setEntity(se);
|
CloseableHttpResponse response = client.execute(post);
|
resData = EntityUtils.toString(response.getEntity());
|
// 检验返回码
|
int statusCode = response.getStatusLine().getStatusCode();
|
if(statusCode != HttpStatus.SC_OK){
|
logger.error("请求出错: "+statusCode);
|
if (statusCode == 307) {
|
Header header = response.getFirstHeader("Location"); // 跳转的目标地址是在 HTTP-HEAD上
|
String newuri = header.getValue(); // 这就是跳转后的地址,再向这个地址发出新申请
|
logger.error(newuri);
|
|
post = new HttpPost(newuri);
|
StringEntity newstringentity = new StringEntity(data,
|
ContentType.create("application/json", "UTF-8"));
|
post.setEntity(newstringentity);
|
response = client.execute(post);
|
resData = EntityUtils.toString(response.getEntity());
|
logger.error("请求出错: "+response.getStatusLine().getStatusCode());
|
}
|
}
|
client.close();
|
logger.info(resData);
|
} catch (Exception e) {
|
logger.error(e.getMessage(), e);
|
}
|
return resData;
|
}
|
|
|
}
|