HttpClient的简单使用java版 移植可用

发布时间:2024年01月06日

以下是一个使用Java语言中的HttpClient的简单案例,注释详细、配置清晰。这个案例演示如何使用HttpClient发送GET和POST请求。

1. 创建HttpClientUtil工具类

// HttpClientUtil.java

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpClientUtil {

    private static final String BASE_URL = "https://jsonplaceholder.typicode.com"; // 替换为实际的API基础URL

    private final HttpClient httpClient;

    public HttpClientUtil() {
        this.httpClient = HttpClients.createDefault();
    }

    /**
     * 发送GET请求
     *
     * @param endpoint API端点
     * @return 响应字符串
     * @throws IOException
     */
    public String sendGetRequest(String endpoint) throws IOException {
        String url = BASE_URL + endpoint;
        HttpGet httpGet = new HttpGet(url);

        try {
            HttpResponse response = httpClient.execute(httpGet);
            return EntityUtils.toString(response.getEntity());
        } finally {
            httpGet.releaseConnection();
        }
    }

    /**
     * 发送POST请求
     *
     * @param endpoint API端点
     * @param requestBody 请求体
     * @return 响应字符串
     * @throws IOException
     */
    public String sendPostRequest(String endpoint, String requestBody) throws IOException {
        String url = BASE_URL + endpoint;
        HttpPost httpPost = new HttpPost(url);

        // 设置请求体
        httpPost.setEntity(new StringEntity(requestBody));

        try {
            HttpResponse response = httpClient.execute(httpPost);
            return EntityUtils.toString(response.getEntity());
        } finally {
            httpPost.releaseConnection();
        }
    }
}

2. 创建Main类演示用法

// Main.java

import java.io.IOException;

public class Main {

    public static void main(String[] args) {
        HttpClientUtil httpClientUtil = new HttpClientUtil();

        try {
            // 发送GET请求
            String getData = httpClientUtil.sendGetRequest("/todos/1");
            System.out.println("GET Response: " + getData);

            // 发送POST请求
            String postData = httpClientUtil.sendPostRequest("/posts", "{ \"title\": \"foo\", \"body\": \"bar\", \"userId\": 1 }");
            System.out.println("POST Response: " + postData);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

请确保你的项目中包含了Apache HttpClient的依赖。你可以通过Maven或Gradle添加如下依赖:

Maven:Maven的:

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

Gradle:Gradle:

implementation 'org.apache.httpcomponents:httpclient:4.5.13'

这个案例使用了Apache HttpClient 4.5.13版本。根据实际需求,你可能需要进一步定制和扩展。

文章来源:https://blog.csdn.net/dongjietao/article/details/135420039
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。