import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
//import org.apache.commons.httpclient.HttpClient;
//import org.apache.commons.httpclient.methods.PostMethod;
//import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.Args;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* http请求 get&post 简单封装的工具类
*/
public class HttpRequestUtil {
// static Logger logger = LoggerFactory.getLogger("HttpRequestUtil");
private static final String DEFAULT_CHARSET = "UTF-8";
private static int timeout = 10000;
/**
* 执行Get请求
* @param url url地址
* @return 返回数据
*/
public static String doGet(String url) {
try {
return Request.Get(url).connectTimeout(timeout).execute().returnContent().asString(Consts.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 执行Get请求
* @param url url地址
* @param paramMap 请求参数
* @return 返回数据
*/
public static String doGet(String url, Map<String, String> paramMap) {
return doGet(url, null, null, null, paramMap);
}
/**
* 执行Get请求
* @param url url地址
* @param hostName 代理的ip
* @param port 代理的端口
* @param schemeName 代理类型http默认
* @param paramMap 参数
* @return responseString
*/
public static String doGet(String url, String hostName, Integer port, String schemeName,
Map<String, String> paramMap) {
return executeGet(url, hostName, port, schemeName, paramMap);
}
private static String executeGet(String url, String hostName, Integer port, String schemeName,
Map<String, String> paramMap) {
Args.notNull(url, "url");
url = buildGetParam(url, paramMap);
Request request = Request.Get(url).connectTimeout(timeout);
request = buildProxy(request, hostName, port, schemeName);
try {
return request.execute().returnContent().asString(Consts.UTF_8);
} catch (IOException e) {
// logger.error(e.getMessage(), e.toString());
}
return null;
}
private static String buildGetParam(String url, Map<String, String> paramMap) {
Args.notNull(url, "url");
if (paramMap != null && !paramMap.isEmpty()) {
List<NameValuePair> paramList = new ArrayList<NameValuePair>(paramMap.size());
for (Map.Entry<String, String> entry : paramMap.entrySet()){
paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
// 拼接参数
url += "?" + URLEncodedUtils.format(paramList, Consts.UTF_8);
}
return url;
}
/**
* 执行post请求
* @param url url地址
* @return resopnseString
*/
public static String doPost(String url) {
return doPost(url, null);
}
/**
* 执行 post 方法
* @param url url地址
* @param param 请求参数
* @return 返回数据
*/
public static String doPostMapParams(String url, Map<String, String> param){
if (MapUtils.isEmpty(param)){
return doPost(url);
}else{
List<NameValuePair> nameValuePairs = new ArrayList<>(param.size());
param.forEach((k, v) -> nameValuePairs.add(new BasicNameValuePair(k, v)) );
return doPost(url, nameValuePairs);
}
}
public static String doPost(String url, List<NameValuePair> nameValuePairs) {
return doPost(url, null, null, null, nameValuePairs, null);
}
public static void doPost(String url, List<NameValuePair> nameValuePairs, List<File> files) {
doPost(url, null, null, null, nameValuePairs, files);
}
public static String doPost(String url, String hostName, Integer port, String schemeName,
List<NameValuePair> nameValuePairs, List<File> files) {
return executePost(url, hostName, port, schemeName, nameValuePairs, files);
}
public static String doPostStringData(String url, String stringData) {
Args.notNull(url, "url");
HttpEntity entity = new StringEntity(stringData, DEFAULT_CHARSET);
Request request = Request.Post(url).body(entity);
try {
return request.execute().returnContent().asString(Consts.UTF_8);
} catch (IOException e) {
// logger.error(e.getMessage(), e.toString());
}
return null;
}
private static String executePost(String url, String hostName, Integer port, String schemeName,
List<NameValuePair> nameValuePairs, List<File> files) {
Args.notNull(url, "url");
HttpEntity entity = buildPostParam(nameValuePairs, files);
Request request = Request.Post(url).connectTimeout(timeout).body(entity);
request = buildProxy(request, hostName, port, schemeName);
try {
return request.execute().returnContent().asString(Consts.UTF_8);
} catch (IOException e) {
// logger.error(e.getMessage(), e.toString());
}
return null;
}
/**
* 构建POST方法请求参数
*
* @return
*/
private static HttpEntity buildPostParam(List<NameValuePair> nameValuePairs, List<File> files) {
if (CollectionUtils.isEmpty(nameValuePairs) && CollectionUtils.isEmpty(files)) {
return null;
}
if (CollectionUtils.isNotEmpty(files)) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for (File file : files) {
builder.addBinaryBody(file.getName(), file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
}
for (NameValuePair nameValuePair : nameValuePairs) {
// 设置ContentType为UTF-8,默认为text/plain; charset=ISO-8859-1,传递中文参数会乱码
builder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(),
ContentType.create("text/plain", Consts.UTF_8));
}
return builder.build();
} else {
try {
return new UrlEncodedFormEntity(nameValuePairs, DEFAULT_CHARSET);
} catch (UnsupportedEncodingException e) {
// logger.error(e.getMessage(), e.toString());
}
}
return null;
}
/**
* 设置代理
*
* @param request
* @param hostName
* @param port
* @param schemeName
* @return
*/
private static Request buildProxy(Request request, String hostName, Integer port, String schemeName) {
if (StringUtils.isNotEmpty(hostName) && port != null) {
// 设置代理
if (StringUtils.isEmpty(schemeName)) {
schemeName = HttpHost.DEFAULT_SCHEME_NAME;
}
request.viaProxy(new HttpHost(hostName, port, schemeName));
}
return request;
}
public static String doPostMapParams4Json(String url, Map<String, String> param){
if (MapUtils.isEmpty(param)){
return doPost(url);
}else{
String result = null;
try {
result = Request.Post(url).connectTimeout(timeout)
.bodyString(JSONObject.toJSONString(param), ContentType.APPLICATION_JSON)
.execute().returnContent().asString();
}catch (Exception e){
e.printStackTrace();
}
return result;
}
}
public static String doPostMapParams4Json(String url, String content){
if (StringUtils.isBlank(content)){
return doPost(url);
}else{
String result = null;
try {
result = Request.Post(url)
.bodyString(content, ContentType.APPLICATION_JSON)
.execute().returnContent().asString();
}catch (Exception e){
e.printStackTrace();
}
return result;
}
}
public static String sendPostRequestforXML(String reqURL, String sendData){
String responseContent = null;
RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
System.out.println("url:"+reqURL);
System.out.println("sendData:"+sendData);
HttpPost httpMethod = new HttpPost(reqURL);
StringEntity entity = new StringEntity(sendData, ContentType.APPLICATION_XML);
httpMethod.setEntity(entity);
try (CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
CloseableHttpResponse response = httpClient.execute(httpMethod);){
HttpEntity respentity = response.getEntity();
if (respentity != null)
{
responseContent = EntityUtils.toString(respentity, "utf-8");
}
EntityUtils.consume(respentity);
}catch (Exception e){
e.printStackTrace();
}
// logger.info("与[" + reqURL + "]通信,结果为"+responseContent);
return responseContent;
}
public static String sendPostRequest(String reqURL, String sendData){
String responseContent = null;
RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
//CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
HttpPost httpPost = new HttpPost(reqURL);
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
try{
httpPost.setEntity(new StringEntity(sendData));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (null != entity) {
responseContent = EntityUtils.toString(entity,"UTF-8");
EntityUtils.consume(entity);
}
}catch(Exception e){
// logger.error("与[" + reqURL + "]通信过程中发生异常,堆栈信息如下", e);
}finally{
try {
httpClient.close();//关闭连接,释放资源
} catch (IOException e) {
}
}
// logger.info("与[" + reqURL + "]通信,结果为"+responseContent);
return responseContent;
}
public static byte[] requestEncoding(String urls) throws Exception {
byte[] receiveBytes = new byte[1024];
OutputStream outputStream = null;
InputStream inputStream = null;
try {
// 建立一个HttpURLConnection
URL url = new URL(urls);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setRequestMethod("GET");
httpConnection.setUseCaches(false);
httpConnection.setInstanceFollowRedirects(true);
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.connect();
/*httpConnection.setRequestMethod("Get");
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setAllowUserInteraction(true);*/
//httpConnection.connect();
//接收返回的数据
inputStream = httpConnection.getInputStream();
receiveBytes = readInputStream(inputStream);//得到一个byte数组
httpConnection.disconnect();
} finally {
if (null != outputStream) {
outputStream.close();
}
if (null != inputStream) {
inputStream.close();
}
}
return receiveBytes;
}
public static byte[] requestEncoding(String urls, byte[] requestData) throws Exception {
byte[] receiveBytes = new byte[1024];
OutputStream outputStream = null;
InputStream inputStream = null;
try {
// 建立一个HttpURLConnection
URL url = new URL(urls);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setDoOutput(true);
//httpConnection.setDoInput(true);
httpConnection.setRequestMethod("POST");
httpConnection.setUseCaches(false);
httpConnection.setInstanceFollowRedirects(true);
httpConnection.setRequestProperty("Content-Type", "text/xml,charset=utf-8");
httpConnection.connect();
//发送数据
outputStream = httpConnection.getOutputStream();
outputStream.write(requestData);
outputStream.flush();
outputStream.close();
//接收返回的数据
inputStream = httpConnection.getInputStream();
receiveBytes = readInputStream(inputStream);//得到一个byte数组
httpConnection.disconnect();
} finally {
if (null != outputStream) {
outputStream.close();
}
if (null != inputStream) {
inputStream.close();
}
}
return receiveBytes;
}
public static byte[] readInputStream(InputStream inputStream) throws IOException {
BufferedInputStream bufferedInputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
int byteLenth = -1;
byte[] receiveBytes = new byte[1024];
try {
bufferedInputStream = new BufferedInputStream(inputStream);
byteArrayOutputStream = new ByteArrayOutputStream(); // 请求数据存放对象
while ((byteLenth = bufferedInputStream.read(receiveBytes)) != -1) {
byteArrayOutputStream.write(receiveBytes, 0, byteLenth);
}
receiveBytes = byteArrayOutputStream.toByteArray();//得到一个byte数组
} finally {
if (null != bufferedInputStream) {
bufferedInputStream.close();
}
if (null != byteArrayOutputStream) {
byteArrayOutputStream.close();
}
}
return receiveBytes;
}
// public static String httpSendReceiver(String url, String xml){
// HttpClient httpClient = new HttpClient();
// // 设置要执行的发送方法及参数
// PostMethod postMethod = new PostMethod(url);
// // String returnMsg = "";
// String result = "";
// try {
// postMethod.setRequestEntity(new StringRequestEntity(xml, "text/xml", "GBK"));
// int statusCode = httpClient.executeMethod(postMethod);
// result = postMethod.getResponseBodyAsString();
// //byte[] bodydata = postMethod.getResponseBody();
//
// }
// catch (Exception e) {
// StringWriter sw = new StringWriter();
// e.printStackTrace(new PrintWriter(sw, true));
// String str = sw.toString();
// logger.error("获取电子单证接口error"+str);
// }
// finally {
// postMethod.releaseConnection();
// }
// return result;
// }
}