Apache HttpClient 的简单使用

10 篇文章 0 订阅

依赖引入:

引入依赖:

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>

Get请求和详细的参数解释:

简单使用Get请求

package test;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class Test3 {
    public static void main(String[] args) throws InterruptedException, URISyntaxException {

        //创建默认的客户端,用于发送请求
        HttpClient httpClient = HttpClients.createDefault();

        //创建需要进行请求的地址
        String url = "http://localhost:8080/test/test1";

        //通过URIBuilder构建带有参数的uri
        URI uri = new URIBuilder(url)
                .addParameter("id", "1")
                .build();

        //配置请求设置参数,如果不在这设置请求连接超时,则若服务器不响应则会一直等待服务器响应
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(3000)
                .setSocketTimeout(3000)
                .setConnectionRequestTimeout(3000)
                .build();

        //创建Get请求体
        HttpGet httpGet = new HttpGet(uri);

        //设置请求配置参数, 可以不设置
        httpGet.setConfig(config);

        //设置部分请求头信息,可以不设置,使用默认的
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.134 Safari/537.36 Edg/103.0.1264.71");

        try {

            //通过httpclient客户端进行get请求,并获得响应体
            HttpResponse response = httpClient.execute(httpGet);

            //获得状态返回码
            int statusCode = response.getStatusLine().getStatusCode();

            //通过状态返回码判断响应状态
            if (statusCode == 200) {
                //获取服务器返回的主要信息
                String msg = EntityUtils.toString(response.getEntity());
                System.out.println("服务器的返回信息 => " + msg);
            }

            //关闭请求连接,如果在处理完成后不关闭连接则会一直保持连接,最大保存连接的数量大约为2,
            //这个我是经过我自己的测试的,在第三次请求的时候就一直是报连接超时问题
            //当达到最大连接数时,进行下次请求就可能导致连接超时问题,导致无法进行连接
            //关于这点可以参考https://zhuanlan.zhihu.com/p/85524697这篇博客的一些源码解释
            response.getEntity().getContent().close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}

运行结果:

在这里插入图片描述

Post请求:

同理post请求:

@Test
    public void post() throws IOException {
        HttpClient httpClient = HttpClients.createDefault();
        String uri = "http://localhost:8080/test/test2";
        String json = "{\n" +
                "  \"id\": \"123\",\n" +
                "  \"name\": \"keli\",\n" +
                "  \"value\": \"bengbengzadian\"\n" +
                "}";
        System.out.println("json: " + json);

        //关于httpEntity的创建可以参考:https://blog.csdn.net/nefetaria/article/details/8703346
        HttpEntity httpEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
        HttpPost post = new HttpPost(uri);
        post.setEntity(httpEntity);
        HttpResponse response = httpClient.execute(post);
        System.out.println("服务器返回信息: " + EntityUtils.toString(response.getEntity()));

    }

运行结果:

在这里插入图片描述

作为测试的服务类TestController(Springboot)

package springboot.controller;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springboot.entity.ReqEntity;

@RestController
@RequestMapping("test")
public class TestController {

    @RequestMapping("test1")
    public String test1(String id ) {
        return "hello i am test1" + "your id: " + id;
    }

    @RequestMapping("test2")
    public Object test2(@RequestBody ReqEntity e) {
        System.out.println(e);
        return e;
    }

}

ReqEntity类:

package springboot.entity;

import lombok.Data;

@Data
public class ReqEntity {
    private String id;
    private String name;
    private String value;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值