• 【171】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();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72

    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);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110

    使用方法

    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);
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
  • 相关阅读:
    黑马点评-异步秒杀实现
    redis分布式锁的应用
    python到底是不是数据分析最好的语言
    Java之接口
    2022年华中杯数学建模挑战赛C题矿井提升机钢丝绳的缺陷分析求解全过程文档及程序
    ES6 入门教程 19 Generator 函数的语法 19.8 作为对象属性的 Generator 函数 & 19.9 Generator 函数的this
    管道模式 流处理
    e人e本优盘使用
    Docker高级篇-Docker容器内Redis集群配置
    配置中心 SpringCloud Config
  • 原文地址:https://blog.csdn.net/zhangchao19890805/article/details/125477966