首页 > 其他分享 >HttpClient

HttpClient

时间:2024-08-24 08:52:52浏览次数:14  
标签:请求 paramMap new HttpClient response httpClient

介绍

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

maven坐标

<dependency>

                          <groupId>org.apache.httpcomponents</groupId>

                         <artifactId>httpclient</artifactId>

                         <version>4.5.13</version>

</dependency>

核心API:

HttpClient

HttpClients

CloseableHttpClient

HttpGet

HttpPost

发送请求步骤:

创建HttpClient对象

创建Http请求对象

调用HttpClient的execute方法发送请求

在idea中操作

测试HttpClient发送Get请求,在测试类中进行测试,前提是项目要运行起来。

测试的接口必须是get请求的

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class HttpClientTest {
    /**
     * 测试HttpClient发送Get请求
     */
    @Test
    public void testGet() throws Exception{
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建Http请求对象
        HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");
        //调用HttpClient对象的execute方法发送请求
        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();

    }

测试结果:

测试HttpClient发送Post请求,在测试类中进行测试,前提是项目要运行起来。

测试的接口必须是Post请求的

/**
     * 测试HttpClient发送Post请求
     */
    @Test
    public void testPost() throws Exception{
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建Http请求对象
        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");
        //调用HttpClient对象的execute方法发送请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        //获取服务端响应的状态码
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("服务端返回的状态码:"+statusCode);
        HttpEntity httpEntity = response.getEntity();
        String body = EntityUtils.toString(httpEntity);
        System.out.println("服务端返回的内容:"+body);
        //关闭资源
        response.close();
        httpClient.close();
    }

测试结果:

一般在项目中如果要发送HTTP请求我们可以创建一个工具类来使用以下是我编写的工具类

/**
 * Http工具类
 */
public class HttpClientUtil {

    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 {
            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);

            //判断响应状态
            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方式请求
     *
     * @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;
    }

    private static RequestConfig builderRequestConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(TIMEOUT_MSEC)
                .setConnectionRequestTimeout(TIMEOUT_MSEC)
                .setSocketTimeout(TIMEOUT_MSEC).build();
    }

}

标签:请求,paramMap,new,HttpClient,response,httpClient
From: https://blog.csdn.net/m0_69501959/article/details/141430056

相关文章

  • C# HttpClient 公共类
    HttpClientService.cs:///<summary>///HTTP请求方法///兼容微信支付V3版本api请求///</summary>publicclassHttpClientService{privatestaticHttpClientService_instance;privatestaticreadonlyobject_lock=ne......
  • HttpClient、IHttpClientFactory、HttpClientHandler 和 HttpMessageHandler 的生命周
    在C#中,HttpClient、IHttpClientFactory、HttpClientHandler和HttpMessageHandler的生命周期密切相关,它们共同影响着网络请求的性能、资源管理和可靠性。以下是它们的生命周期分析:1.HttpClient的生命周期默认行为:HttpClient是线程安全的,设计为可以在应用程序的整个生命......
  • 在高并发和高负载场景下,优化 HttpClient
    在高并发和高负载场景下,优化HttpClient的使用至关重要,因为不当的资源管理可能导致性能瓶颈、资源枯竭(如端口耗尽)、和请求延迟等问题。以下是一些优化建议:1.使用IHttpClientFactory管理HttpClient实例复用HttpMessageHandler:通过IHttpClientFactory创建HttpClient实......
  • 在 C# 中处理 HttpClient 实例时,使用单例模式和 IHttpClientFactory,DNS缓存问题
    在C#中处理HttpClient实例时,使用单例模式和IHttpClientFactory都有各自的优缺点,尤其是在高并发情况下。以下是它们的对比及性能考虑:1.单例模式使用HttpClient优势:减少资源消耗:HttpClient是设计为复用的类,创建一个单例可以避免频繁创建和销毁HttpClient实例,从而减......
  • IHttpClientFactory 解决端口耗尽问题及衍生底层原理
    1.IHttpClientFactory解决端口耗尽问题问题描述:如果不使用IHttpClientFactory,而是为每个请求创建新的HttpClient实例,可能会导致端口耗尽问题。原因:每次创建新的HttpClient实例都会导致新的HttpClientHandler和底层Socket连接的创建,且这些连接在短时间内无法被回......
  • C# httpclient上传文件
    ///<summary>///上传文件///</summary>///<paramname="file"></param>///<returns></returns>[HttpPost,Route("UploadFile")][NonAuthorize]publicasyncTask<Response<string>>UploadFile......
  • httpclient&WebClient--4次迭代,让我的 Client 优化 100倍!
    4次迭代,让我的Client优化100倍!https://www.cnblogs.com/crazymakercircle/p/17136216.html 在大家的生产项目中,经常需要通过Client组件(HttpClient/OkHttp/JDKConnection)调用第三方接口。在一个高并发的中台生产项目中。有一个比较特殊的请求,一次请求,包含10个Web外部......
  • java httpclient发送中文乱码
    在使用Java的HttpClient发送请求时,如果遇到中文乱码问题,通常需要确保请求和响应的字符集都正确设置为UTF-8。以下是一些解决方法:指定请求数据的字符集为UTF-8格式:在使用UrlEncodedFormEntity或StringEntity时,确保传递正确的字符集参数。例如:StringEntityentity=newUrlEnco......
  • Angular项目如何使用拦截器 httpClient 请求响应处理
    在Angular中,拦截器(Interceptor)是一种用于拦截和处理HTTP请求或响应的机制。HttpClient模块提供了一种方便的方式来创建拦截器,以便在发送请求或接收响应之前或之后执行一些操作。以下是如何在Angular项目中使用HttpClient拦截器的基本步骤:创建拦截器类:首先,你需要创建一个继承自H......
  • Apache HttpClient发送文件时中文名变问号
    使用ApacheHttpClient发送multipart/form-data,包含有中文名的文件,对方收到的文件名中文变成了问号解决方法:发送方需要设置mode为HttpMultipartMode.RFC6532发送端代码如下,其中关键行为builder.setMode(HttpMultipartMode.RFC6532);importorg.apache.http.HttpEntity;impor......