JAVA8发送带有Body的HTTPGET请求
正常来讲,按照Http标准,GET请求事不能带有消息体BODY的。但是HTTP标准不是硬性规定,各个厂商可以根据自己的需求做成灵活的扩展。比如ES的搜索接口就要求客户端发送带有BODY的HTTP GET请求。
发送请求的代码分成两个类,接收返回数据的 StrResponse 和发起请求的工具栏 HttpUtils
StrResponse.java
import java.util.List;
import java.util.Map;
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.*;
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请求内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关文章