JAVA8發(fā)送帶有Body的HTTP GET請求
正常來講,按照HTTP標(biāo)準(zhǔn),GET請求事不能帶有消息體BODY的。但是HTTP標(biāo)準(zhǔn)不是硬性規(guī)定,各個(gè)廠商可以根據(jù)自己的需求做成靈活的擴(kuò)展。比如ES的搜索接口就要求客戶端發(fā)送帶有BODY的HTTP GET請求。
發(fā)送請求的代碼分成兩個(gè)類,接收返回?cái)?shù)據(jù)的 StrResponse 和發(fā)起請求的工具欄 HttpUtils
StrResponse.java
import java.util.List;
import java.util.Map;
/**
?* 接收HTTP返回?cái)?shù)據(jù)的對象
?* @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發(fā)送方法
?*
?* @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);
? ? ? ? ? ? // 請求內(nèi)容的長度
? ? ? ? ? ? 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作為字節(jié)流寫入post請求的body中
? ? ? ? ? ? connection.setDoOutput(true);
? ? ? ? ? ? if (null != requestBody && requestBody.length > 0) {
? ? ? ? ? ? ? ? connection.getOutputStream().write(requestBody);
? ? ? ? ? ? }
? ? ? ? ? ? // 定義 BufferedReader輸入流來讀取URL的響應(yīng)
? ? ? ? ? ? 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的響應(yīng)
? ? ? ? ? ? ? ? ? ? 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) {
? ? ? ? // 字符串轉(zhuǎn)成字節(jié)流
? ? ? ? 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);
}
}
到此這篇關(guān)于JAVA8發(fā)送帶有Body的HTTP GET請求的文章就介紹到這了,更多相關(guān)JAVA8發(fā)送HTTP GET請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
帶你了解如何使用Spring基于ProxyFactoryBean創(chuàng)建AOP代理
這篇文章主要介紹了Spring基于ProxyFactoryBean創(chuàng)建AOP代理,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2021-08-08
Java編程中的性能優(yōu)化如何實(shí)現(xiàn)
這篇文章主要介紹了Java編程中的性能優(yōu)化如何實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10
java實(shí)現(xiàn)簡單解析XML文件功能示例
這篇文章主要介紹了java實(shí)現(xiàn)簡單解析XML文件功能,結(jié)合實(shí)例形式分析了java針對xml文件的讀取、遍歷節(jié)點(diǎn)及輸出等相關(guān)操作技巧,需要的朋友可以參考下2017-10-10
教你怎么在IDEA中創(chuàng)建java多模塊項(xiàng)目
這篇文章主要介紹了教你怎么在IDEA中創(chuàng)建java多模塊項(xiàng)目,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-04-04
基于Java設(shè)計(jì)一個(gè)高并發(fā)的秒殺系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了如何基于Java設(shè)計(jì)一個(gè)高并發(fā)的秒殺系統(tǒng),文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,有需要的小伙伴可以參考下2023-10-10

