HttpClient教程

简介:

HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

导入依赖(pom.xml)

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

核心API:

1. HttpClient:Http的客户端,可以发送http请求(是一个接口)

2. HttpClients:是一个构建器,可以创建HttpClient对象

3. CloseableHttpClient:具体的实现类,用于实现HttpClient

4. HttpGet:Http的Get请求

5.HttpPost:Http的Post请求


发送请求的步骤

1.创建HttpClient对象

2.创建Http对象

3.通过HttpClient的execute发送请求


HttpClient工具类

package com.sky.utils;

import com.alibaba.fastjson.JSONObject;
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.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Http工具类,用于发送HTTP GET和POST请求。
 */
public class HttpClientUtil {

    // 设置请求超时时间为5秒
    static final int TIMEOUT_MSEC = 5 * 1000;

    /**
     * 发送GET方式请求
     * @param url 请求地址
     * @param paramMap 请求参数键值对
     * @return 响应内容
     */
    public static String doGet(String url, Map<String, String> paramMap) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String result = "";
        CloseableHttpResponse response = null;

        try {
            // 构建请求URI
            URIBuilder builder = new URIBuilder(url);
            if (paramMap != null) {
                for (String key : paramMap.keySet()) {
                    builder.addParameter(key, paramMap.get(key));
                }
            }
            URI uri = builder.build();

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

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

            // 判断响应状态,如果状态码为200,表示请求成功
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            // 捕获并打印异常
            e.printStackTrace();
        } finally {
            try {
                // 关闭响应和客户端
                response.close();
                httpClient.close();
            } catch (IOException e) {
                // 捕获并打印关闭资源时的异常
                e.printStackTrace();
            }
        }

        return result;
    }

    /**
     * 发送POST方式请求
     * @param url 请求地址
     * @param paramMap 请求参数键值对
     * @return 响应内容
     * @throws IOException 网络异常
     */
    public static String doPost(String url, Map<String, String> paramMap) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            // 创建参数列表
            if (paramMap != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }

            // 设置请求配置
            httpPost.setConfig(builderRequestConfig());

            // 执行http请求
            response = httpClient.execute(httpPost);

            // 获取响应内容
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            // 抛出异常
            throw e;
        } finally {
            try {
                // 关闭响应
                response.close();
            } catch (IOException e) {
                // 捕获并打印关闭资源时的异常
                e.printStackTrace();
            }
        }

        return resultString;
    }

    /**
     * 发送POST方式请求,适用于JSON格式数据
     * @param url 请求地址
     * @param paramMap 请求参数键值对
     * @return 响应内容
     * @throws IOException 网络异常
     */
    public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            if (paramMap != null) {
                // 构造json格式数据
                JSONObject jsonObject = new JSONObject();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    jsonObject.put(param.getKey(), param.getValue());
                }
                StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");
                // 设置请求编码
                entity.setContentEncoding("utf-8");
                // 设置数据类型
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }

            // 设置请求配置
            httpPost.setConfig(builderRequestConfig());

            // 执行http请求
            response = httpClient.execute(httpPost);

            // 获取响应内容
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            // 抛出异常
            throw e;
        } finally {
            try {
                // 关闭响应
                response.close();
            } catch (IOException e) {
                // 捕获并打印关闭资源时的异常
                e.printStackTrace();
            }
        }

        return resultString;
    }

    /**
     * 构建请求配置
     * @return RequestConfig对象
     */
    private static RequestConfig builderRequestConfig() {
        // 设置连接超时、请求超时和套接字超时时间
        return RequestConfig.custom()
                .setConnectTimeout(TIMEOUT_MSEC)
                .setConnectionRequestTimeout(TIMEOUT_MSEC)
                .setSocketTimeout(TIMEOUT_MSEC)
                .build();
    }

}
​​​​​​​

实现案例-GEt请求

 // 创建httpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建请求对象
        HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");
        //执行请求
        CloseableHttpResponse response = httpClient.execute(httpGet);
        //获取响应码
        System.out.println("返回的状态码"+response.getStatusLine().getStatusCode());
        //获取响应实体
        HttpEntity entity = response.getEntity();
        //获取响应实体内容
        String string = EntityUtils.toString(entity);
        //打印内容
        System.out.println("服务端返回的数据:"+string);
        //关闭
        response.close();
        httpClient.close();

实现案例-POST请求

@Test
    public void postHttpTest() throws IOException {
        //创建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 stringEntity=new StringEntity(jsonObject.toString(),"UTF-8");
        stringEntity.setContentType("application/json");
        httpPost.setEntity(stringEntity);
        //发送请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        //解析响应请求数据
        HttpEntity entity = response.getEntity();
        String string = EntityUtils.toString(entity);
        System.out.println(string);
        //关闭连接
        response.close();
        httpClient.close();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值