HttpClient 简单示例

本文详细介绍了如何在Java中通过ApacheHttpClient库发送GET和POST请求到指定URL,包括创建HttpClient实例、创建请求方法、设置请求头、执行请求并处理响应。

 在Java中,使用Apache HttpClient库发起一个GET请求到指定网址的基本步骤如下:

maven依赖

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

get

// 导入相关依赖
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;

public class SimpleHttpClient {

    public static void main(String[] args) throws Exception {
        // 步骤1: 创建HttpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 步骤2: 创建HttpGet请求
        String targetUrl = "http://example.com/api/data";
        HttpGet httpGet = new HttpGet(targetUrl);

        // 可选步骤3: 添加请求头 (例如,身份验证或内容类型)
        // httpGet.setHeader("Authorization", "Bearer your_token");
        
        // 步骤4: 执行请求
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            // 步骤5: 获取响应状态码
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                // 步骤6: 获取响应实体内容
                String content = EntityUtils.toString(response.getEntity());
                System.out.println("Response Content: " + content);
            } else {
                System.out.println("Error Code : " + statusCode);
            }
        }

        // 步骤7: 关闭HttpClient实例(推荐在finally块中确保关闭资源)
        // httpClient.close(); // 在try-with-resources语句中自动关闭
    }
}

post

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.ContentType;

public class SimpleHttpClient {

    public static void main(String[] args) throws Exception {
        // 步骤1: 创建HttpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 步骤2: 创建HttpPost请求
        String targetUrl = "http://example.com/api/data";
        HttpPost httpPost = new HttpPost(targetUrl);

        // 步骤3: 创建请求体(这里假设是JSON格式的数据)
        String jsonInputString = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
        HttpEntity entity = new StringEntity(jsonInputString, ContentType.APPLICATION_JSON);

        // 步骤4: 设置HttpPost请求体
        httpPost.setEntity(entity);

        // 可选步骤5: 添加请求头,如Content-Type等
        httpPost.setHeader("Content-type", "application/json");

        // 步骤6: 执行请求
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            // 步骤7: 获取响应状态码
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                // 步骤8: 获取响应实体内容
                String content = EntityUtils.toString(response.getEntity());
                System.out.println("Response Content: " + content);
            } else {
                System.out.println("Error Code : " + statusCode);
            }
        }

        // 步骤9: 关闭HttpClient实例(推荐在try-with-resources语句中自动关闭)
        // httpClient.close(); // 在try-with-resources语句中自动关闭
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值