Java 发送 Http 请求工具类(HttpClient)

import com.gientech.util.LoggerUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;

/**
 *
 * HttpClient
 * @author xiarg
 * @date 2023/11/1 17:18
 */
public class TdspHttpClient {

    private static final Logger logger = LoggerFactory.getLogger(TdspHttpClient.class);

    @Autowired
    private CloseableHttpClient httpClient;

    public TdspHttpClient() {
        httpClient = HttpClients.createDefault();
    }

    public String sendGetRequest(String url) throws IOException {
        LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>接口请求start<<<<<===== {0}", url);
        HttpEntity entity = null;
        String result = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpGet);
            entity = response.getEntity();
            result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>接口请求返回结果<<<<<===== {0}",
                    result);
        } catch (IOException e) {
            LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>发送出现异常<<<<<===== {0}",
                    e.getMessage());
            e.printStackTrace();
        } catch (ParseException e) {
            LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>发送出现异常<<<<<===== {0}",
                    e.getMessage());
            e.printStackTrace();
        } finally {
            EntityUtils.consume(entity);
        }
        return result;
    }

    public String sendPostRequest(String url, String requestBody, String contentType) throws IOException {
        LoggerUtil.info(logger, "[HttpClientUtils.sendPostRequest]=====>>>>>接口请求start<<<<<===== {0}", url);
        HttpEntity entity = null;
        String result = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new StringEntity(requestBody, ContentType.create(contentType, StandardCharsets.UTF_8)));
            HttpResponse response = httpClient.execute(httpPost);
            entity = response.getEntity();
            result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>接口请求返回结果<<<<<===== {0}",
                    result);
        } catch (UnsupportedCharsetException e) {
            LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>发送出现异常<<<<<===== {0}",
                    e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>发送出现异常<<<<<===== {0}",
                    e.getMessage());
            e.printStackTrace();
        } catch (ParseException e) {
            LoggerUtil.info(logger, "[HttpClientUtils.sendGetRequest]=====>>>>>发送出现异常<<<<<===== {0}",
                    e.getMessage());
            e.printStackTrace();
        } finally {
            EntityUtils.consume(entity);
        }
        return result;
    }

    public static void main(String[] args) {
        TdspHttpClient httpClientUtils = new TdspHttpClient();

        // 发送 application/x-www-form-urlencoded 格式的 POST 请求
        try {
            String postUrl1 = "https://example.com/api1";
            String requestBody1 = "param1=value1¶m2=value2";
            String contentType1 = "application/x-www-form-urlencoded";

            String postResponse1 = httpClientUtils.sendPostRequest(postUrl1, requestBody1, contentType1);
            System.out.println("POST Response (application/x-www-form-urlencoded): " + postResponse1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 发送 application/json 格式的 POST 请求
        try {
            String postUrl2 = "https://example.com/api2";
            String requestBody2 = "{\"param1\": \"value1\", \"param2\": \"value2\"}";
            String contentType2 = "application/json";

            String postResponse2 = httpClientUtils.sendPostRequest(postUrl2, requestBody2, contentType2);
            System.out.println("POST Response (application/json): " + postResponse2);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 发送 application/xml 格式的 POST 请求
        try {
            String postUrl3 = "https://example.com/api3";
            String requestBody3 = "value1value2";
            String contentType3 = "application/xml";

            String postResponse3 = httpClientUtils.sendPostRequest(postUrl3, requestBody3, contentType3);
            System.out.println("POST Response (application/xml): " + postResponse3);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

        此工具类可以直接复制使用。

你可能感兴趣的:(开发,java,http,开发语言)