java httpclient工具类
2020-12-13 05:07
标签:超时 print dep pos lib tom deb amp exec meven -- 代码 java httpclient工具类 标签:超时 print dep pos lib tom deb amp exec 原文地址:https://www.cnblogs.com/baobaoxiaokeai/p/11130947.htmlimport com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.*;
/**
* HttpClient4.3工具类
*/
@Slf4j
public class HttpClientUtils {
private static RequestConfig requestConfig = null;
private static String charset = "utf-8";
public static void main(String[] args) {
JSONObject tt = new JSONObject();
tt.put("aaa", "4444");
Map mm = new HashMap();
mm.put("aaa", "555");
//System.out.println("result:" + httpPost("http://127.0.0.1:8761/hi1", tt));
// System.out.println("result:" + httpPost("http://127.0.0.1:8761/hi1", mm));
//System.out.println("result:" + httpPost("http://127.0.0.1:8761/hi1", JSON.toJSONString(mm)));
System.out.println("result:" + httpPostForm("http://127.0.0.1:8761/hi2", mm));
}
static {
// 设置请求和传输超时时间
requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
}
/**
* @param url
* @param obj 1. json字符串 2. map 3.JSONObject
* @return JSONObject
*/
public static JSONObject httpPost(String url, Object obj) {
// post请求返回结果
CloseableHttpClient httpClient = HttpClients.createDefault();
JSONObject jsonResult = null;
HttpPost httpPost = new HttpPost(url);
// 设置请求和传输超时时间
httpPost.setConfig(requestConfig);
try {
if (null != obj) {
StringEntity entity = null;
if (obj instanceof String) {
entity = new StringEntity(obj.toString(), charset);
} else {
entity = new StringEntity(JSON.toJSONString(obj), charset);
}
entity.setContentEncoding(charset);
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
log.debug(" {} - {} ", url, obj);
CloseableHttpResponse response = httpClient.execute(httpPost);
return convertResponse(response);
} catch (Exception e) {
log.error("error HttpClientUtils {} - {} - {}" + url, obj, e);
} finally {
httpPost.releaseConnection();
}
return jsonResult;
}
/**
* post请求传输String参数 例如:name=Jack&sex=1&type=2
* Content-type:application/x-www-form-urlencoded
*
* @param url url地址
* @param
* @return
*/
public static JSONObject httpPostForm(String url, Map