簡單get/post方法http請求工具類,帶head引數
阿新 • • 發佈:2019-02-15
package com.***.util; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import com.w3china.mingjing3.JsonResult; import com.w3china.mingjing3.isp.Constants; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; 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.client.methods.HttpRequestBase; import org.apache.http.client.utils.URIBuilder; 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; public class HttpClientUtil { private static PoolingHttpClientConnectionManager cm; private static String UTF_8 = "UTF-8"; private static void init() { if (cm == null) { cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(50);// 整個連線池最大連線數 cm.setDefaultMaxPerRoute(5);// 每路由最大連線數,預設值是2 } } /** * 通過連線池獲取HttpClient */ private static CloseableHttpClient getHttpClient() { init(); return HttpClients.custom().setConnectionManager(cm).build(); } private static ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) { ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>(); for (Map.Entry<String, Object> param : params.entrySet()) { pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue()))); } return pairs; } //列印一下引數,並根據傳送型別判斷 public static JsonResult<String> HttpRequest(String type,String url, Map<String, Object> paramMap) throws IOException, URISyntaxException { Map<String, Object> params = new HashMap<>(); for (Map.Entry<String, Object> entry : paramMap.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); params.put(entry.getKey(), entry.getValue()); } if (type.equalsIgnoreCase("post")) { return postHttp(url, params); } else { return getHttp(url, params); } } //post請求 public static JsonResult<String> postHttp(String url, Map<String, Object> params) throws IOException { HttpPost httpPost = new HttpPost(url); // 如果需要head資訊的話 // 多添一個引數 Map<String, Object> headers // for (Map.Entry<String, Object> param : headers.entrySet()) { // httpPost.addHeader(param.getKey(), String.valueOf(param.getValue())); // } ArrayList<NameValuePair> pairs = covertParams2NVPS(params); httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8)); CloseableHttpClient httpClient = getHttpClient(); CloseableHttpResponse response = httpClient.execute(httpPost); return getHttpStatusOrEntity(response); } //get請求 public static JsonResult<String> getHttp(String url, Map<String, Object> params) throws URISyntaxException, IOException { URIBuilder ub = new URIBuilder(); ub.setPath(url); ArrayList<NameValuePair> pairs = covertParams2NVPS(params); ub.setParameters(pairs); HttpGet httpGet = new HttpGet(ub.build()); // 如果需要head資訊 // 多傳 Map<String, Object> headers引數 // for (Map.Entry<String, Object> param : headers.entrySet()) { // httpGet.addHeader(param.getKey(), String.valueOf(param.getValue())); //} CloseableHttpClient httpClient = getHttpClient(); CloseableHttpResponse response = httpClient.execute(httpGet); return getHttpStatusOrEntity(response); } //判斷狀態碼是否成功 成功則返回資料 public static JsonResult<String> getHttpStatusOrEntity( CloseableHttpResponse response) throws IOException { int statusCode = response.getStatusLine().getStatusCode();//狀態碼 HttpEntity entity = response.getEntity();// 獲取返回實體 String res= EntityUtils.toString(entity); response.close(); switch (statusCode){ case 200://:代表請求成功 return JsonResult.ok(res); case 303://:代表重定向 return JsonResult.error(303,res); case 400://:代表請求錯誤 return JsonResult.error(400,res); case 401://:代表未授權 return JsonResult.error(401,res); case 403://:代表禁止訪問 return JsonResult.error(403,res); case 404://:代表檔案未找到\ return JsonResult.error(404,res); case 500://:代表伺服器錯誤 return JsonResult.error(500,res); default://其他 return JsonResult.error(statusCode,res); } } }
返回工具類
public class JsonResult<T> { private boolean success; private int errCode; private String errMsg = ""; private T data; private List<T> list; //set get... //記得寫預設的構造方法 //ok構造引數 public static <T> JsonResult<T> ok(T result) { return new JsonResult<T>(result); } public JsonResult(T result) { this.success=true; this.errCode = 0; this.errMsg = "OK"; this.data = result; } //error public static <T> JsonResult<T> error(int code ,String result) { return new JsonResult<T>( code , result); } public JsonResult(int code ,String result) { this.success=false; this.errCode = code; this.errMsg = result; } }
使用程式碼
//引數賦值
String url="http://.....";
Map<String, Object> map = new HashMap<>();
//使用
HttpClientUtil.HttpRequest("get", url, map);