1. 程式人生 > >Java HttpClient4.2.x版本get、post請求工具類

Java HttpClient4.2.x版本get、post請求工具類

ont char cat time exec con lai pla names

公司業務需要,跟很多公司合作,經常需要請求外部http接口,而項目架構是一個比較老的框架整合,僅http請求的工具類就很多個,顯得雜亂無章;

有些接口測試時,對方做了IP白名單限制的,ZIP壓縮等要求,現有的http工具類無法滿足要求,又不能去修改,因為很多地方在用;想引入最新HttpClient版本的依賴,確發現與現有的jar包沖突;

無耐只能使用現有的jar重新封裝,具體代碼演示如下:

post請求方式1

/**
* POST請求,超時時間必須設置
* @param url
* @param json JSON數據格式傳參
* @return
*/
public static String post(String url, String json) {
String result = null;
HttpClient httpClient = null;
HttpPost httpPost = null;

try {
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(url);
// 連接超時設置
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
// 讀取超時設置
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);

StringEntity stringEntity = new StringEntity(json, Consts.UTF_8);
stringEntity.setContentEncoding(Consts.UTF_8.toString());
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);

HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (null != entity) {
result = EntityUtils.toString(entity, Consts.UTF_8);
}
} catch (Exception e) {
e.printStackTrace();
result = JSON.toJSONString(Result.error(e.getMessage()));
} finally {
// 終止本次請求
httpPost.abort();
// 釋放連接
httpPost.releaseConnection();
httpClient.getConnectionManager().shutdown();
}

return result;
}

post請求方式2

/**
* POST請求,超時時間必須設置
* @param url
* @param params
* @return
*/
public static String post(String url, Map<String, String> params) {
String result = null;
HttpClient httpClient = null;
HttpPost httpPost = null;

try {
List<NameValuePair> pairs = new ArrayList<>();
for (Entry<String, String> entry : params.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(url);
// 連接超時設置
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
// 讀取超時設置
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);

StringEntity stringEntity = new UrlEncodedFormEntity(pairs, Consts.UTF_8);
httpPost.setEntity(stringEntity);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
httpPost.setHeader("Accept", "text/plain;charset=utf-8");
httpPost.setHeader("Accept-Encoding", "gzip, deflate");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (null != entity) {
result = EntityUtils.toString(entity, Consts.UTF_8);
}
} catch (Exception e) {
e.printStackTrace();
result = JSON.toJSONString(Result.error(e.getMessage()));
} finally {
// 終止本次請求
httpPost.abort();
// 釋放連接
httpPost.releaseConnection();
httpClient.getConnectionManager().shutdown();
}

return result;
}

get請求

/**
* GET請求,超時時間必須設置
* @param url
* @param params Map<String, String>數據格式傳參
* @return
*/
public static String get(String url, Map<String, String> params) {
String result = null;
HttpClient httpClient = null;
HttpGet httpGet = null;

try {
List<NameValuePair> pairs = new ArrayList<>();
for (Entry<String, String> entry : params.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
URI uri = new URI(url + "?" + URLEncodedUtils.format(pairs, Consts.UTF_8));

httpClient = new DefaultHttpClient();
httpGet = new HttpGet(uri);

// 連接超時設置
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
// 讀取超時設置
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);

HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
result = EntityUtils.toString(entity, Consts.UTF_8);
}
} catch (Exception e) {
e.printStackTrace();
result = JSON.toJSONString(Result.error(e.getMessage()));
} finally {
httpGet.abort();
httpGet.releaseConnection();
httpClient.getConnectionManager().shutdown();
}

return result;
}

post請求代理方式

/**
* GET請求,超時時間必須設置
* @param url
* @param params Map<String, String>數據格式傳參
* @return
*/
public static String get(String url, Map<String, String> params) {
String result = null;
HttpClient httpClient = null;
HttpGet httpGet = null;

try {
List<NameValuePair> pairs = new ArrayList<>();
for (Entry<String, String> entry : params.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
URI uri = new URI(url + "?" + URLEncodedUtils.format(pairs, Consts.UTF_8));

httpClient = new DefaultHttpClient();
httpGet = new HttpGet(uri);

// 連接超時設置
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
// 讀取超時設置
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);

HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
result = EntityUtils.toString(entity, Consts.UTF_8);
}
} catch (Exception e) {
e.printStackTrace();
result = JSON.toJSONString(Result.error(e.getMessage()));
} finally {
httpGet.abort();
httpGet.releaseConnection();
httpClient.getConnectionManager().shutdown();
}

return result;
}

Java HttpClient4.2.x版本get、post請求工具類