java通过httpclient封装类,发送http请求

发布时间 2023-12-25 15:24:55作者: 竹狼

一、导入pom依赖

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

二、封装post和get请求方法

package com.kye.utils;


import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
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.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

@Slf4j
public class HttpUtils {

    /**
     * @param url 请求的url
     * @param map 请求时参数会自动变为key1=value1&key2=value2,contentType也会自动变为application/x-www-form-urlencoded
     * @return 获取相应内容
     */
    //map入参
    public static String PostUrlEncoded(String url, Map<String, String> map) throws IOException {
        //创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建请求方法的实例
        HttpPost httpPost = new HttpPost();
        try {
            httpPost.setURI(new URI(url));
        } catch (URISyntaxException e) {
            e.getMessage();
        }
        //设置传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();
        httpPost.setConfig(requestConfig);
        //添加请求参数
        ArrayList<NameValuePair> arrayList = new ArrayList<>();
        Set<Map.Entry<String, String>> entrySet = map.entrySet();
        for (Map.Entry<String, String> entry : entrySet) {
            String key = entry.getKey();
            String value = entry.getValue();
            arrayList.add(new BasicNameValuePair(key, value));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(arrayList));
        //发送http请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        //获取返回的内容
        String result;
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            result = EntityUtils.toString(response.getEntity());
        } else {
            log.info("请求接口出现错误,状态码为:{}", statusCode);
            return null;
        }
        return result;
    }

    /**
     * 封装POST请求(String入参)
     *
     * @param url  请求的路径
     * @param data String类型json格式数据
     * @return 获取相应内容
     */
    public static String postJson(String url, String data) throws IOException {
        //创建HttpClient对象
        HttpClient httpClient = HttpClientBuilder.create().build();
        //创建请求方式的实例
        HttpPost httpPost = new HttpPost(url);
        //添加请求参数(设置请求和传输超时时间)
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        //设置请求头
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        //设置请求参数
        httpPost.setEntity(new StringEntity(data, "UTF-8"));
        //发送Http请求
        HttpResponse response = httpClient.execute(httpPost);
        //获取返回的内容
        String result;
        int statusCode = response.getStatusLine().getStatusCode();
        if (200 == statusCode) {
            result = EntityUtils.toString(response.getEntity());
        } else {
            log.info("请求接口出现错误,状态码为:{}", statusCode);
            return null;
        }
        return result;
    }

    /**
     * 封装GET请求
     *
     * @param url 请求地址
     * @return 相应内容
     */
    public static String get(String url) throws IOException {
        //1、创建HttpClient对象
        HttpClient httpClient = HttpClientBuilder.create().build();
        //2、创建请求方式的实例
        HttpGet httpGet = new HttpGet(url);
        //3、添加请求参数(设置请求和传输超时时间)
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
        httpGet.setConfig(requestConfig);
        //4、发送Http请求
        HttpResponse response = httpClient.execute(httpGet);
        //5、获取返回的内容
        String result;
        int statusCode = response.getStatusLine().getStatusCode();
        if (200 == statusCode) {
            result = EntityUtils.toString(response.getEntity());
        } else {
            log.info("请求接口出现错误,状态码为:{}", statusCode);
            return null;
        }
        return result;
    }
}