JAVA8發送帶有Body的HTTP GET請求
正常來講,按照HTTP標準,GET請求事不能帶有消息體BODY的。但是HTTP標準不是硬性規定,各個廠商可以根據自己的需求做成靈活的擴展。比如ES的搜索接口就要求客戶端發送帶有BODY的HTTP GET請求。
發送請求的代碼分成兩個類,接收返回數據的 StrResponse 和發起請求的工具欄 HttpUtils
StrResponse.java
import java.util.List; import java.util.Map; /** * 接收HTTP返回數據的對象 * @author zhangchao */ public class StrResponse { private int code = 200; private Map<String, List<String>> headers = null; private String body = null; public Map<String, List<String>> getHeaders() { return headers; } public String getBody() { return body; } public void setHeaders(Map<String, List<String>> headers) { this.headers = headers; } public void setBody(String body) { this.body = body; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getHeaderStr (String key) { List<String> list = this.headers.get(key); StringBuilder sb = new StringBuilder(); for (String str : list) { sb.append(str); } return sb.toString(); } public String getAllHeaderStr() { if (null == headers || headers.isEmpty()) { return ""; } StringBuilder sb = new StringBuilder(); for (String key : headers.keySet()) { List<String> list = headers.get(key); sb.append(key + ":\n"); for (String str : list) { sb.append(" " + str + "\n"); } } return sb.toString(); } @Override public String toString() { final StringBuffer sb = new StringBuffer("StrResponse{"); sb.append("code=").append(code); sb.append(", headers=").append(headers); sb.append(", body='").append(body).append('\''); sb.append('}'); return sb.toString(); } }
HttpUtils.java
import java.util.Map; import java.util.List; import java.io.*; import java.net.*; /** * 通用http發送方法 * * @author zhangchao */ public class HttpUtils { public static StrResponse requestByte_responseStr(final String url, final String method, final byte[] requestBody,final Map<String, String> headerMap, String responseEncoding) { BufferedReader in = null; BufferedReader errorReader = null; HttpURLConnection connection = null; StrResponse strResponse = null; try { StringBuilder result = new StringBuilder(); URL realUrl = new URL(url); // 打開和URL之間的連接 connection = (HttpURLConnection) realUrl.openConnection(); connection.setRequestMethod(method); // 請求內容的長度 if (null != requestBody && requestBody.length > 0) { connection.setRequestProperty("Content-Length", String.valueOf(requestBody.length)); } // 自定義請求頭 if (null != headerMap && false == headerMap.isEmpty()) { Set<String> keySet = headerMap.keySet(); for (String key : keySet) { connection.setRequestProperty(key, headerMap.get(key)); } } connection.setConnectTimeout(5000); connection.setReadTimeout(5000); // 把JSON作為字節流寫入post請求的body中 connection.setDoOutput(true); if (null != requestBody && requestBody.length > 0) { connection.getOutputStream().write(requestBody); } // 定義 BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader( connection.getInputStream(), responseEncoding)); String line; while ((line = in.readLine()) != null) { result.append(line).append("\n"); } strResponse = new StrResponse(); strResponse.setCode(connection.getResponseCode()); // 返回的header Map<String, List<String>> map = connection.getHeaderFields(); strResponse.setHeaders(map); // 返回的body String responseBody = result.toString(); strResponse.setBody(responseBody); } catch (Exception e) { e.printStackTrace(); try { if (null != connection) { StringBuilder result = new StringBuilder(); // 定義 BufferedReader輸入流來讀取URL的響應 errorReader = new BufferedReader(new InputStreamReader( connection.getErrorStream(), responseEncoding)); String line; while ((line = errorReader.readLine()) != null) { result.append(line).append("\n"); } strResponse = new StrResponse(); strResponse.setCode(connection.getResponseCode()); // 返回的header Map<String, List<String>> map = connection.getHeaderFields(); strResponse.setHeaders(map); // 返回的body String responseBody = result.toString(); strResponse.setBody(responseBody); } } catch (Exception e2) { e2.printStackTrace(); } } finally { try { if (null != in) { in.close(); } if (null != errorReader) { errorReader.close(); } } catch (IOException e) { e.printStackTrace(); } } return strResponse; } public static StrResponse requestStr_responseStr(final String url, final String method, final String requestBody, final Map<String, String> headerMap, final String encoding) { // 字符串轉成字節流 byte[] bodyBytes = null; try { if (requestBody != null) { bodyBytes = requestBody.getBytes(encoding); } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } return requestByte_responseStr(url, method, bodyBytes, headerMap, encoding); } }
使用方法
public class Main{ public static void main(String[] args) { String url = "http://192.168.19.11:9200/yourindex/_search"; String requestBody = "{" + "\"query\": {" + " \"bool\": {" + " \"must\": [" + " {" + " \"term\": {" + " \"areaName.keyword\": \"" + areaName + "\"" + " }" + " }," + " {" + " \"term\": {" + " \"date.keyword\": \"" + date+ "\"" + " }" + " }," + " {" + " \"term\": {\"rytype.keyword\": \"root\"}" + " }" + " ]" + " }" + " " + " }" + "}"; Map<String, String> headerMap = new HashMap<>(); headerMap.put("Content-Type", "application/json"); headerMap.put("Referer", url); String encoding = "UTF-8"; StrResponse strResponse = HttpUtils.requestStr_responseStr(url, "GET", requestBody, headerMap, encoding); String body = strResponse.getBody(); logger.info(body); } }
到此這篇關於JAVA8發送帶有Body的HTTP GET請求的文章就介紹到這瞭,更多相關JAVA8發送HTTP GET請求內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- 關於BufferedReader的讀取效率問題
- 使用ServletInputStream在攔截器或過濾器中應用後重寫
- Java Process與Runtime()的使用及調用cmd命令阻塞的解決方案
- Java字符串拼接的優雅方式實例詳解
- Java發起http請求的完整步驟記錄