• Java实现发送Get、Post请求仅需两步


    前言

    普通Java程序想要发送Get、Post等请求可以采用HttpClient实现,下面给出HttpClient使用方法,并已经封装成方法,直接拿去用即可

    准备工作

    在maven中导入依赖:

    		<dependency>
                <groupId>org.apache.httpcomponentsgroupId>
                <artifactId>httpmimeartifactId>
                <version>4.5.13version> 
            dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    Get请求

    记得在类中写上一个静态变量:private static HttpClient client = HttpClients.createDefault();

    	/**
         * 发送HttpGet请求
         * @param url 请求的url
         * @param params get请求携带的参数
         * @param headers 请求头需要额外携带的参数
         * @return Sting格式的响应结果
         */
        public static String Get(String url, HashMap<String, String> params, HashMap<String, String> headers) {
    
            HttpGet httpGet = new HttpGet();
    
            // 设置请求头
            httpGet.addHeader("Accept", "application/json");
            httpGet.addHeader("Accept-Language", "zh-CN,zh;q=0.9");
            httpGet.addHeader("Connection", "keep-alive");
            httpGet.addHeader("Content-Type", "application/json; charset=utf-8");
            httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36");
    
            if (headers != null && headers.size() > 0) {
                headers.forEach(httpGet::addHeader);
            }
    
            // 设置参数
            if (params != null && params.size() > 0) {
                StringBuilder newUrl = new StringBuilder(url + "?");
                params.forEach((k, v) -> newUrl.append(k).append("=").append(v).append("&"));
                httpGet.setURI(URI.create(newUrl.toString()));
            }
    
            String response;
            try {
                HttpResponse execute = client.execute(httpGet);
                // 获取响应实体
                HttpEntity responseEntity = execute.getEntity();
                response = responseEntity != null ? EntityUtils.toString(responseEntity, "UTF-8") : "响应结果为null";
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
    
            return response;
        }
    
    • 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

    Post请求

    记得在类中写上一个静态变量:private static HttpClient client = HttpClients.createDefault();

    	/**
         * 发送HttpPost请求
         * @param url 请求的url
         * @param payloads post请求携带的请求体
         * @param headers 请求头需要额外携带的参数
         * @return Sting格式的响应结果
         */
        public static String Post(String url, HashMap<String, String> payloads, HashMap<String, String> headers) {
    
            HttpPost httpPost = new HttpPost(url);
    
            // 设置请求头
            httpPost.addHeader("Accept", "application/json");
            httpPost.addHeader("Accept-Language", "zh-CN,zh;q=0.9");
            httpPost.addHeader("Connection", "keep-alive");
            httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36");
    
            if (headers != null && headers.size() > 0) {
                headers.forEach(httpPost::addHeader);
            }
    
            // 构建请求体参数
            if (payloads != null && payloads.size() > 0) {
                MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
                payloads.forEach((k, v) -> {
                    if (k.equals("Boundary")) {
                        entityBuilder.setBoundary(v);
                    } else {
                        entityBuilder.addTextBody(k, v);
                    }
                });
    
                httpPost.setEntity(entityBuilder.build());
            }
    
            String response;
            try {
                HttpResponse execute = client.execute(httpPost);
                // 获取响应实体
                HttpEntity responseEntity = execute.getEntity();
                response = responseEntity != null ? EntityUtils.toString(responseEntity, "UTF-8") : "响应结果为null";
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
    
            return response;
        }
    
    • 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
  • 相关阅读:
    C++初阶(十)模板初阶
    R2R 的一些小tip
    Linux 常见问题
    小米软件开发二面和中兴软开一面
    从成本到灵活性:ddos防御的真正价值
    含文档+PPT+源码等]精品spring boot+MySQL客户关系管理系统vue[包运行成功]SpringBoot毕业设计程序设计项目源码
    前端,HTTP协议,HTML介绍
    Spring Boot常用注解@ConfigurationProperties、松散绑定、数据校验
    实习day1
    [Flask]Pycharm+Flask零基础项目搭建入门
  • 原文地址:https://blog.csdn.net/java_cpp_/article/details/133376956