HttpClient

1、基本使用步骤

  1. 引入依赖:在项目中添加 HTTPclient 的依赖,如果使用 Maven,可以在pom.xml文件中添加如下依赖:
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>
  1. 创建 HttpClient 实例:通常使用CloseableHttpClient来创建一个可关闭的 HTTP 客户端实例。可以通过HttpClients工具类来创建,如:
CloseableHttpClient httpClient = HttpClients.createDefault();
  1. 创建 HttpUriRequest 实例:根据不同的 HTTP 请求方法,创建相应的请求实例,如HttpGetHttpPost等。例如创建一个 GET 请求:
HttpGet httpGet = new HttpGet("https://example.com/api/data");
  1. 执行请求 execute方法:使用HttpClient实例执行请求,并获取响应。

CloseableHttpResponse response = httpClient.execute(httpGet);
  1. 处理响应:从响应中获取状态码、响应头、响应体等信息。

try {
    // 获取状态码
    int statusCode = response.getStatusLine().getStatusCode();
    System.out.println("Status Code: " + statusCode);

    // 获取响应头
    Header[] headers = response.getAllHeaders();
    for (Header header : headers) {
        System.out.println(header.getName() + ": " + header.getValue());
    }

    // 获取响应体
    HttpEntity entity = response.getEntity();
    if (entity!= null) {
        String responseBody = EntityUtils.toString(entity, "UTF-8");
        System.out.println("Response Body: " + responseBody);
    }
} finally {
    // 关闭响应和客户端
    response.close();
    httpClient.close();
}

2、案例

2.1 Get方法案例

/**
     * 测试通过httpclient发送GET方式的请求
     */
    public void testGET() throws Exception{
        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //创建请求对象
        HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");

        //发送请求,接受响应结果
        CloseableHttpResponse response = httpClient.execute(httpGet);

        //获取服务端返回的状态码
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("服务端返回的状态码为:" + statusCode);

        HttpEntity entity = response.getEntity();
        String body = EntityUtils.toString(entity);
        System.out.println("服务端返回的数据为:" + body);

        //关闭资源
        response.close();
        httpClient.close();
    }
}

2.2 Post方法请求:

相比GET请求来说,POST请求若携带参数需要封装请求体对象,并将该对象设置在请求对象中。

public void testPOST() throws Exception{
        // 创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //创建请求对象
        HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username","admin");
        jsonObject.put("password","123456");

        StringEntity entity = new StringEntity(jsonObject.toString());
        //指定请求编码方式
        entity.setContentEncoding("utf-8");
        //数据格式
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        //发送请求
        CloseableHttpResponse response = httpClient.execute(httpPost);

        //解析返回结果
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("响应码为:" + statusCode);

        HttpEntity entity1 = response.getEntity();
        String body = EntityUtils.toString(entity1);
        System.out.println("响应数据为:" + body);

        //关闭资源
        response.close();
        httpClient.close();
    }

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇