以下代碼包括最基本的GET、POST、JSON參數的POST方式的請求。(相當於POSTMAN中使用raw編寫的參數)
package com.chinecredit.eccis.utils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; 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.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.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 org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSONObject; /** * http訪問方法實現 * @author 王俊南 * @date: 2018-11-22 */ public class HttpRequestUtils { private static Logger logger = LoggerFactory .getLogger(HttpRequestUtils.class); // 日誌記錄 /** * GET提交 * * @return */ public static String doGet(String url) { String strResult = ""; // 1. 創建一個默認的client實例 CloseableHttpClient client = HttpClients.createDefault(); try { // 2. 創建一個httpget對象 HttpGet httpGet = new HttpGet(url); System.out.println("executing GET request " + httpGet.getURI()); // 3. 執行GET請求並獲取響應對象 CloseableHttpResponse resp = client.execute(httpGet); try { // 6. 打印響應長度和響應內容 if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 4. 獲取響應體 HttpEntity entity = resp.getEntity(); System.out.println("Response content length = " + entity.getContentLength()); System.out.println("------"); strResult = EntityUtils.toString(resp.getEntity()); } } finally { //無論請求成功與否都要關閉resp resp.close(); } } catch (ClientProtocolException e) { logger.error("get請求失敗:", e); // e.printStackTrace(); } catch (ParseException e) { logger.error("get請求解析出錯:", e); // e.printStackTrace(); } catch (IOException e) { logger.error("get請求IO出錯:", e); // e.printStackTrace(); } finally { // 8. 最終要關閉連接,釋放資源 try { client.close(); } catch (Exception e) { logger.error("get請求完畢關閉連接出錯:", e); // e.printStackTrace(); } } return strResult; } /** * 普通POST提交 * @param url * @param map * @return */ public static String doPost(String url, Map<String, Object> map) { String strResult = ""; // 1. 獲取默認的client實例 CloseableHttpClient client = HttpClients.createDefault(); // 2. 創建httppost實例 HttpPost httpPost = new HttpPost(url); // 3. 創建參數隊列(鍵值對列表) List<NameValuePair> paramPairs = new ArrayList<>(); Set<String> keySet = map.keySet(); for (String key : keySet) { Object val = map.get(key); paramPairs.add(new BasicNameValuePair(key, val.toString())); } UrlEncodedFormEntity entity; try { // 4. 將參數設置到entity對象中 entity = new UrlEncodedFormEntity(paramPairs, "UTF-8"); // 5. 將entity對象設置到httppost對象中 httpPost.setEntity(entity); // 6. 發送請求並回去響應 CloseableHttpResponse resp = client.execute(httpPost); try { // 7. 獲取響應entity HttpEntity respEntity = resp.getEntity(); strResult = EntityUtils.toString(respEntity, "UTF-8"); } finally { // 9. 關閉響應對象 resp.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 10. 關閉連接,釋放資源 try { client.close(); } catch (Exception e) { e.printStackTrace(); } } return strResult; } /** * json參數方式POST提交 * @param url * @param params * @return */ public static String doPost(String url, JSONObject params){ String strResult = ""; // 1. 獲取默認的client實例 CloseableHttpClient client = HttpClients.createDefault(); // 2. 創建httppost實例 HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Content-Type", "application/json;charset=utf-8"); //添加請求頭 try { httpPost.setEntity(new StringEntity(params.toJSONString(),"utf-8")); CloseableHttpResponse resp = client.execute(httpPost); try { // 7. 獲取響應entity HttpEntity respEntity = resp.getEntity(); strResult = EntityUtils.toString(respEntity, "UTF-8"); } finally { resp.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { client.close(); } catch (Exception e) { e.printStackTrace(); } } return strResult; } }