iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >JAVA8发送带有Body的HTTPGET请求
  • 805
分享到

JAVA8发送带有Body的HTTPGET请求

2024-04-02 19:04:59 805人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

正常来讲,按照Http标准,GET请求事不能带有消息体BODY的。但是HTTP标准不是硬性规定,各个厂商可以根据自己的需求做成灵活的扩展。比如ES的搜索接口就要求客户端发送带有BOD

正常来讲,按照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请求内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: JAVA8发送带有Body的HTTPGET请求

本文链接: https://www.lsjlt.com/news/152739.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作