/** * 發送post請求 * @param url 路徑 * @param jsonObject 參數(json類型) * @param encoding 編碼格式 * @return * @throws ParseException * @throws IOException */ public static String send(String url, JSONObject jsonObject,String encoding) throws ParseException, IOException{ String body = ""; //創建httpclient對象 CloseableHttpClient client = HttpClients.createDefault(); //創建post方式請求對象 HttpPost httpPost = new HttpPost(url); //裝填參數 StringEntity s = new StringEntity(jsonObject.toString(), "utf-8"); s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); //設置參數到請求對象中 httpPost.setEntity(s); System.out.println("請求地址:"+url); // System.out.println("請求參數:"+nvps.toString()); //設置header信息 //指定報文頭【Content-type】、【User-Agent】 // httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); httpPost.setHeader("Content-type", "application/json"); httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //執行請求操作,並拿到結果(同步阻塞) CloseableHttpResponse response = client.execute(httpPost); //獲取結果實體 HttpEntity entity = response.getEntity(); if (entity != null) { //按指定編碼轉換結果實體為String類型 body = EntityUtils.toString(entity, encoding); } EntityUtils.consume(entity); //釋放鏈接 response.close(); return body; }
下面代碼自己寫。
2019/11/18,看到代碼挺多人看的,再給大家提供一個Http工具類,數據提交包括 Raw,Json等
package com.xiaojiang.checkin.utils; import com.alibaba.fastjson.JSONObject; import com.xiaojiang.checkin.entity.HttpClientResult; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.*; import org.apache.http.client.utils.URIBuilder; 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.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.*; /** * Description: httpClient工具類 * * @author JourWon * @date Created on 2018年4月19日 */ public class HttpClientUtils { // 編碼格式。發送編碼格式統一用UTF-8 private static final String ENCODING = "UTF-8"; // 設置連接超時時間,單位毫秒。 private static final int CONNECT_TIMEOUT = 6000; // 請求獲取數據的超時時間(即響應時間),單位毫秒。 private static final int SOCKET_TIMEOUT = 6000; /** * 發送get請求;不帶請求頭和請求參數 * * @param url 請求地址 * @return * @throws Exception */ public static HttpClientResult doGet(String url) throws Exception { return doGet(url, null, null); } /** * 發送get請求;帶請求參數 * * @param url 請求地址 * @param params 請求參數集合 * @return * @throws Exception */ public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception { return doGet(url, null, params); } /** * 發送get請求;帶請求頭和請求參數 * * @param url 請求地址 * @param headers 請求頭集合 * @param params 請求參數集合 * @return * @throws Exception */ public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception { // 創建httpClient對象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 創建訪問的地址 URIBuilder uriBuilder = new URIBuilder(url); if (params != null) { Set<Map.Entry<String, String>> entrySet = params.entrySet(); for (Map.Entry<String, String> entry : entrySet) { uriBuilder.setParameter(entry.getKey(), entry.getValue()); } } // 創建http對象 HttpGet httpGet = new HttpGet(uriBuilder.build()); /** * setConnectTimeout:設置連接超時時間,單位毫秒。 * setConnectionRequestTimeout:設置從connect Manager(連接池)獲取Connection * 超時時間,單位毫秒。這個屬性是新加的屬性,因為目前版本是可以共享連接池的。 * setSocketTimeout:請求獲取數據的超時時間(即響應時間),單位毫秒。 如果訪問一個接口,多少時間內無法返回數據,就直接放棄此次調用。 */ RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build(); httpGet.setConfig(requestConfig); // 設置請求頭 packageHeader(headers, httpGet); // 創建httpResponse對象 CloseableHttpResponse httpResponse = null; try { // 執行請求並獲得響應結果 return getHttpClientResult(httpResponse, httpClient, httpGet); } finally { // 釋放資源 release(httpResponse, httpClient); } } /** * 發送post請求;不帶請求頭和請求參數 * * @param url 請求地址 * @return * @throws Exception */ public static HttpClientResult doPost(String url) throws Exception { return doPost(url, null, null); } /** * 發送post請求;帶請求參數 * * @param url 請求地址 * @param params 參數集合 * @return * @throws Exception */ public static HttpClientResult doPost(String url, Map<String, String> params) throws Exception { return doPost(url, null, params); } /** * 發送post請求;帶請求頭和請求參數 *可發送Formdata數據,請把請求頭設置一下,不然獲取不到數據。 * @param url 請求地址 * @param headers 請求頭集合 * @param params 請求參數集合 * @return * @throws Exception */ public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception { // 創建httpClient對象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 創建http對象 HttpPost httpPost = new HttpPost(url); /** * setConnectTimeout:設置連接超時時間,單位毫秒。 * setConnectionRequestTimeout:設置從connect Manager(連接池)獲取Connection * 超時時間,單位毫秒。這個屬性是新加的屬性,因為目前版本是可以共享連接池的。 * setSocketTimeout:請求獲取數據的超時時間(即響應時間),單位毫秒。 如果訪問一個接口,多少時間內無法返回數據,就直接放棄此次調用。 */ RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build(); httpPost.setConfig(requestConfig); // 設置請求頭 /*httpPost.setHeader("Cookie", ""); httpPost.setHeader("Connection", "keep-alive"); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9"); httpPost.setHeader("Accept-Encoding", "gzip, deflate, br"); httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/ packageHeader(headers, httpPost); // 封裝請求參數 packageParam(params, httpPost); // 創建httpResponse對象 CloseableHttpResponse httpResponse = null; try { // 執行請求並獲得響應結果 return getHttpClientResult(httpResponse, httpClient, httpPost); } finally { // 釋放資源 release(httpResponse, httpClient); } } /*** * 發送post請求封裝formdata * */ // public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params){ // // } /** * 發送POST請求帶Raw參數 * */ public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params,String raw) throws Exception { // 創建httpClient對象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 創建http對象 HttpPost httpPost = new HttpPost(url); //封裝raw 參數 packageRaw(raw,httpPost); /** * setConnectTimeout:設置連接超時時間,單位毫秒。 * setConnectionRequestTimeout:設置從connect Manager(連接池)獲取Connection * 超時時間,單位毫秒。這個屬性是新加的屬性,因為目前版本是可以共享連接池的。 * setSocketTimeout:請求獲取數據的超時時間(即響應時間),單位毫秒。 如果訪問一個接口,多少時間內無法返回數據,就直接放棄此次調用。 */ RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build(); httpPost.setConfig(requestConfig); // 設置請求頭 /*httpPost.setHeader("Cookie", ""); httpPost.setHeader("Connection", "keep-alive"); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9"); httpPost.setHeader("Accept-Encoding", "gzip, deflate, br"); httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/ packageHeader(headers, httpPost); // 封裝請求參數 packageParam(params, httpPost); // 創建httpResponse對象 CloseableHttpResponse httpResponse = null; try { // 執行請求並獲得響應結果 return getHttpClientResult(httpResponse, httpClient, httpPost); } finally { // 釋放資源 release(httpResponse, httpClient); } } /*** * 發送Post有些這封裝代碼 * 封裝formdata數據 */ public static void packageFormData(Map<String,String> params,HttpEntityEnclosingRequestBase HttpMethod){ List<NameValuePair> paramList = new ArrayList <NameValuePair>(); if(params != null && params.size() > 0){ Set<String> keySet = params.keySet(); for(String key : keySet) { paramList.add(new BasicNameValuePair(key, params.get(key))); } } HttpMethod.setEntity(new UrlEncodedFormEntity(paramList,Charset.forName("UTF-8"))); System.out.println(paramList); } /** * 封裝Raw數據 * */ public static void packageRaw(String raw,HttpEntityEnclosingRequestBase HttpMethod){ try { //傳map進來需要自己封裝key,val StringEntity postingString = new StringEntity(raw);// json傳遞 HttpMethod.setEntity(postingString); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } /** * 發送put請求;不帶請求參數 * * @param url 請求地址 * @return * @throws Exception */ public static HttpClientResult doPut(String url) throws Exception { return doPut(url); } /** * 發送put請求;帶請求參數 * * @param url 請求地址 * @param params 參數集合 * @return * @throws Exception */ public static HttpClientResult doPut(String url, Map<String, String> params) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPut httpPut = new HttpPut(url); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build(); httpPut.setConfig(requestConfig); packageParam(params, httpPut); CloseableHttpResponse httpResponse = null; try { return getHttpClientResult(httpResponse, httpClient, httpPut); } finally { release(httpResponse, httpClient); } } /** * 發送delete請求;不帶請求參數 * * @param url 請求地址 * @return * @throws Exception */ public static HttpClientResult doDelete(String url) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpDelete httpDelete = new HttpDelete(url); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build(); httpDelete.setConfig(requestConfig); CloseableHttpResponse httpResponse = null; try { return getHttpClientResult(httpResponse, httpClient, httpDelete); } finally { release(httpResponse, httpClient); } } /** * 發送delete請求;帶請求參數 * * @param url 請求地址 * @param params 參數集合 * @return * @throws Exception */ public static HttpClientResult doDelete(String url, Map<String, String> params) throws Exception { if (params == null) { params = new HashMap<String, String>(); } params.put("_method", "delete"); return doPost(url, params); } /** * Description: 封裝請求頭 * @param params * @param httpMethod */ public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) { // 封裝請求頭 if (params != null) { Set<Map.Entry<String, String>> entrySet = params.entrySet(); for (Map.Entry<String, String> entry : entrySet) { // 設置到請求頭到HttpRequestBase對象中 httpMethod.setHeader(entry.getKey(), entry.getValue()); } } } /** * Description: 封裝請求參數 * * @param params * @param httpMethod * @throws UnsupportedEncodingException */ public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod) throws UnsupportedEncodingException { // 封裝請求參數 if (params != null) { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); Set<Map.Entry<String, String>> entrySet = params.entrySet(); for (Map.Entry<String, String> entry : entrySet) { nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } // 設置到請求的http對象中 httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING)); } } /** * Description: 獲得響應結果 * * @param httpResponse * @param httpClient * @param httpMethod * @return * @throws Exception */ public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception { // 執行請求 httpResponse = httpClient.execute(httpMethod); // 獲取返回結果 if (httpResponse != null && httpResponse.getStatusLine() != null) { String content = ""; if (httpResponse.getEntity() != null) { content = EntityUtils.toString(httpResponse.getEntity(), ENCODING); } return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(),content); } return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR); } /** * Description: 釋放資源 * * @param httpResponse * @param httpClient * @throws IOException */ public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException { // 釋放資源 if (httpResponse != null) { httpResponse.close(); } if (httpClient != null) { httpClient.close(); } } }