【Java】HttpClient訪問Restful Api(Http)

使用該工具類(HttpUtils)可直接調用API訪問,如果爲Https方式訪問請查看我另一篇博文,後面還有更多Java相關知識,請關注我的CSDN博客互相學習。。,有什麼問題也可以加我QQ:444623631,互相討論。

 

package com.smart.mvc.util;

 


import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
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;


/**
 * HTTP 請求工具類
 * 
 * @author ldd
 * @date 2017年7月27日
 *
 */
public class HttpUtils {
private static PoolingHttpClientConnectionManager connMgr;
private static RequestConfig requestConfig;
private static final int MAX_TIMEOUT = 7000;

static {
// 設置連接池
connMgr = new PoolingHttpClientConnectionManager();
// 設置連接池大小
connMgr.setMaxTotal(100);
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());


RequestConfig.Builder configBuilder = RequestConfig.custom();
// 設置連接超時
configBuilder.setConnectTimeout(MAX_TIMEOUT);
// 設置讀取超時
configBuilder.setSocketTimeout(MAX_TIMEOUT);
// 設置從連接池獲取連接實例的超時
configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
// 在提交請求之前 測試連接是否可用
configBuilder.setStaleConnectionCheckEnabled(true);
requestConfig = configBuilder.build();
}


/**
* 發送 POST 請求,JSON形式,獲取所有請求頭
* @param apiUrl
* @param json
* @return
*/
public static Map<String, String> doHeader(String apiUrl, Object json) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
Map<String, String> temp = new HashMap<>();


try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解決中文亂碼問題
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
Header[] headers = response.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
temp.put(headers[i].getName(), headers[i].getValue());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return temp;
}

/**
* 發送 GET 請求
* @param url
* @return
*/
public static String doGet(String url) {
return doGet(new HashMap<>(), url, new HashMap<>());
}

/**
* 發送 GET 請求,並攜帶Token
* @param headers
* @param url
* @return
*/
public static String doGet(String tokenId, String url) {
//設置固定請求頭
Map<String, String> headers = new HashMap<>();
headers.put("X-Auth-Token", tokenId);
return doGet(headers, url, new HashMap<>());
}

/**
* 發送 GET 請求,K-V形式,並可攜帶多個請求頭
* @param headers
* @param url
* @param params
* @return
*/
public static String doGet(Map<String, String> headers, String url, Map<String, Object> params) {
String apiUrl = url;
StringBuffer param = new StringBuffer();
int i = 0;
for (String key : params.keySet()) {
if (i == 0)
param.append("?");
else
param.append("&");
param.append(key).append("=").append(params.get(key));
i++;
}
apiUrl += param;
String result = null;
HttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet(apiUrl);
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
HttpResponse response = httpclient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();


System.out.println("執行狀態碼 : " + statusCode);


HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}


/**
* 發送 POST 請求,K-V形式,並可攜帶多個請求頭
* @param headers
* @param apiUrl
* @param params
* @return
*/
public static String doPost(Map<String, String> headers, String apiUrl, Map<String, Object> params) {
System.out.println(apiUrl);


CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;


try {
httpPost.setConfig(requestConfig);
List<NameValuePair> pairList = new ArrayList<>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
pairList.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
response = httpClient.execute(httpPost);
System.out.println(response.toString());
HttpEntity entity = response.getEntity();
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}

/**
* 發送 POST 請求,並攜帶Token
* @param tokenId
* @param apiUrl
* @param json
* @return
*/
public static String doPost(String tokenId, String apiUrl) {
//設置固定請求頭
Map<String, String> headers = new HashMap<>();
headers.put("X-Auth-Token", tokenId);
return doPost(headers, apiUrl, new HashMap<>());
}

/**
* 發送 POST 請求,JSON形式 ,並攜帶Token
* @param tokenId
* @param apiUrl
* @param json
* @return
*/
public static String doPost(String tokenId, String apiUrl, String json) {
//設置固定請求頭
Map<String, String> headers = new HashMap<>();
headers.put("X-Auth-Token", tokenId);
return doPost(headers, apiUrl, json);
}


/**
* 發送 POST 請求,JSON形式 ,並可攜帶多個請求頭
* @param headers
* @param apiUrl
* @param json
* @return
*/
public static String doPost(Map<String, String> headers, String apiUrl, String json) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;


try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解決中文亂碼問題
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine().getStatusCode());
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}

/**
* 發送 Delete 請求,並攜帶Token
* @param tokenId
* @param apiUrl
* @return
*/
public static String doDelete(String tokenId, String apiUrl) {
Map<String, String> headers = new HashMap<>();
headers.put("X-Auth-Token", tokenId);
return doDelete(headers, apiUrl);
}

/**
* 發送 Delete 請求,並可以攜帶多個請求頭
* @param headers
* @param apiUrl
* @return
*/
public static String doDelete(Map<String, String> headers, String apiUrl) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpDelete httpDelete = new HttpDelete(apiUrl);
CloseableHttpResponse response = null;


try {
httpDelete.setConfig(requestConfig);
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
response = httpClient.execute(httpDelete);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine().getStatusCode());
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}

/**
* 發送 Put 請求,JSON形式 ,並攜帶Token
* @param tokenId
* @param apiUrl
* @param json
* @return
*/
public static String doPut(String tokenId, String apiUrl, Object json) {
Map<String, String> headers = new HashMap<>();
headers.put("X-Auth-Token", tokenId);
return doPut(headers, apiUrl, json);
}

/**
* 發送 Put 請求,JSON形式 ,並攜帶多個請求頭
* @param headers
* @param apiUrl
* @param json
* @return
*/
public static String doPut(Map<String, String> headers, String apiUrl, Object json) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPut httpPut = new HttpPut(apiUrl);
CloseableHttpResponse response = null;


try {
httpPut.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解決中文亂碼問題
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPut.setEntity(stringEntity);
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPut.setHeader(entry.getKey(), entry.getValue());
}
response = httpClient.execute(httpPut);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine().getStatusCode());
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章