Java基础系列:httpclient请求GET和POST接口

1 简介

1.1 Java请求GET和POST接口

Java请求Http接口常用的方式有三种,如下表

序号工具描述应用案例
1URLConnectionJava原生,java.net.URLConnectionhttps://blog.csdn.net/Xin_101/article/details/122440247
2HttpURLConnectionJava原生,java.net.HttpURLConnectionhttps://blog.csdn.net/Xin_101/article/details/122449254
3httpclient第三方工具,org.apache.httpcomponentshttps://blog.csdn.net/Xin_101/article/details/122449693

本章讲解httpclient请求接口。

1.2 httpclient

原Apache httpclient通用依赖为:commons-httpclient,现已将该功能迁移到:org.apache.httpcomponents

<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>
  • Maven仓库告知如下:

在这里插入图片描述

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

2 接口

表单接口:
在这里插入图片描述

2 测试

2.1 Code

package com.monkey.java_study.web;

import com.google.gson.Gson;
import com.monkey.java_study.common.entity.PageEntity;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;

/**
 * HttpClient请求接口测试样例.
 *
 * @author xindaqi
 * @date 2022-01-12 11:34
 */
public class HttpClientTest {

    private static final Logger logger = LogManager.getLogger(HttpClientTest.class);

    /**
     * GET请求.
     *
     * @param url 请求地址
     * @return 响应数据
     */
    public static String doGet(String url) {
        try {
            // 创建客户端
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            // 建立连接
            HttpGet httpGet = new HttpGet(url);
            // 请求配置:超时时间,单位:毫秒
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
            httpGet.setConfig(requestConfig);
            // 设置请求头:内容类型
            httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");

            return getResponse(httpClientBuilder, httpGet);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * POST请求:携带表单数据form-data.
     *
     * @param url      请求地址
     * @param paramMap 表单数据
     * @return 响应数据
     */
    public static String doPostFormData(String url, Map<String, Object> paramMap) {
        try {
            // 创建客户端
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            // 建立连接
            HttpPost httpPost = new HttpPost(url);
            // 请求配置:超时时间,单位:毫秒
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
            httpPost.setConfig(requestConfig);
            // 设置请求头:内容类型
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            if (Objects.nonNull(paramMap) && !paramMap.isEmpty()) {
                List<NameValuePair> formDataList = new ArrayList<>();
                Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
                for (Map.Entry<String, Object> mapEntry : entrySet) {
                    formDataList.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(formDataList, "UTF-8"));
            }

            return postResponse(httpClientBuilder, httpPost);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * POST请求:携带JSON数据.
     *
     * @param url    请求地址
     * @param params 请求数据:JSON字符串
     * @return 响应数据
     */
    public static String doPostJson(String url, String params) {
        try {
            // 创建客户端
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            // 建立连接
            HttpPost httpPost = new HttpPost(url);
            // 请求配置:超时时间,单位:毫秒
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
            httpPost.setConfig(requestConfig);
            // 设置请求头:内容类型
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            StringEntity stringEntity = new StringEntity(params);
            stringEntity.setContentType("text/json");
            httpPost.setEntity(stringEntity);
            return postResponse(httpClientBuilder, httpPost);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 获取GET请求数据.
     *
     * @param httpClientBuilder 客户端对象
     * @param httpGet           GET请求
     * @return 响应数据
     */
    public static String getResponse(HttpClientBuilder httpClientBuilder, HttpGet httpGet) {
        try (CloseableHttpResponse closeableHttpResponse = httpClientBuilder.build().execute(httpGet)) {
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            return EntityUtils.toString(httpEntity, "UTF-8");
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 获取POST请求数据.
     *
     * @param httpClientBuilder 客户端对象
     * @param httpPost          POST请求
     * @return 响应数据
     */
    public static String postResponse(HttpClientBuilder httpClientBuilder, HttpPost httpPost) {
        try (CloseableHttpResponse closeableHttpResponse = httpClientBuilder.build().execute(httpPost)) {
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            return EntityUtils.toString(httpEntity, "UTF-8");
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public static void main(String[] args) {

        // GET:请求
        String getUrl = "http://localhost:9121/api/v1/mongodb/read?userId=0x001";
        String getResponse = doGet(getUrl);
        logger.info(">>>>>>>>>Get response:{}", getResponse);

        // POST:请求携带form-data参数
        String postFormDataUrl = "http://localhost:9121/api/v1/parameter/annotation/form-data";
        Map<String, Object> mapFormData = new HashMap<>();
        mapFormData.put("name", "xiaohong");
        String formDataResponse = doPostFormData(postFormDataUrl, mapFormData);
        logger.info(">>>>>>>>>Post form data response:{}", formDataResponse);

        // POST:请求携带JSON参数
        String postUrl = "http://localhost:9121/api/v1/mongodb/page";
        // 入参实体
        PageEntity pageEntity = new PageEntity(1, 2);
        Gson gson = new Gson();
        // 实体转JSON字符串
        String jsonString = gson.toJson(pageEntity);
        String postResponse = doPostJson(postUrl, jsonString);
        logger.info(">>>>>>>>>>Post json response:{}", postResponse);
    }
}

2.2 测试

在这里插入图片描述

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
HttpClientJava中的一个开源库,用于支持HTTP协议的客户端编程。它是一个用于发送HTTP请求和接收HTTP响应的包装工具类。HttpClient可以被用于执行GET和POST请求等HTTP方法。走看看是一个基于Web的应用程序,包含了各种常见的网站功能,如搜索、资讯、体育、财经、购物等多个频道。下面将分别介绍HttpClient发送GET和POST请求时的一些重要知识点。 HttpClient发送GET请求时,需要构造一个HttpGet对象,并指定请求的URL。调用HttpClient.execute方法,并且将HttpGet对象传递给该方法。接下来,HttpClient会发送GET请求到指定的URL,然后将响应内容作为一个HttpResponse对象返回给程序。可以从HttpResponse对象中获取响应状态、响应头和响应体等信息。 HttpClient发送POST请求时,需要首先构造一个HttpPost对象,并指定请求的URL。调用HttpPost.setEntity方法来设置请求体内容,然后调用HttpClient.execute方法,并将HttpPost对象传递给该方法。接下来,HttpClient会将POST请求数据发送到指定的URL,然后将响应内容作为一个HttpResponse对象返回给程序。与GET请求相似,可以从HttpResponse对象中获取响应状态、响应头和响应体等信息。 总的来说,HttpClient是一个十分强大和方便的网络编程工具类,可以方便地实现HTTP请求和响应的处理。可以根据自己的需求选择GET和POST请求发送,然后获取响应内容和各种信息。使用HttpClient能够简化开发,提高编程效率,是Java网络编程开发中非常重要的一种库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天然玩家

坚持才能做到极致

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值