您的位置:

Apache HttpComponents详解

一、简介

Apache HttpComponents是一个开源的Java HTTP库,可以用于创建和发送HTTP, HTTPS请求,以及处理HTTP响应。该库最初由Jakarta项目提供,现已成为Apache项目的一部分。Apache HttpComponents包含两个模块:HttpClient和HttpCore。

二、HttpClient模块

HttpClient模块是使用最广泛的HttpComponents模块之一。HttpClient提供了许多功能,包括但不限于:

1、创建和发送HTTP, HTTPS请求。

2、支持连接池和状态管理,以便重用HTTP连接并优化性能。

3、支持异步请求以及回调函数。

三、HttpCore模块

HttpCore模块是HttpClient模块的底层模块。HttpCore提供了HTTP协议的核心功能,包括但不限于:

1、HTTP请求和响应消息的解析和序列化。

2、支持处理HTTP头和HTTP实体。

3、支持HTTP连接的管理和线程安全。

四、使用HttpComponents发送HTTP请求

以下代码示例演示如何使用HttpComponents发送HTTP GET请求:

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 HttpComponentsDemo {
    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet("http://www.example.com/");
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                System.out.println(EntityUtils.toString(entity));
            }
        } finally {
            response.close();
        }
    }
}

上述代码中创建了一个默认的CloseableHttpClient对象。使用HttpGet对象来表示HTTP GET请求,并使用execute方法发送HTTP请求。最后,从HTTP响应中获取实体,并将其转换为字符串以打印响应内容。

五、处理HTTP响应

以下代码示例演示如何处理HTTP响应:

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.apache.http.HttpResponse;

public class HttpComponentsDemo {
    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet("http://www.example.com/");

        HttpResponse response = httpclient.execute(httpget);
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("statusCode=" + statusCode);

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String content = EntityUtils.toString(entity);
            System.out.println("content=" + content);
        }
    }
}

上述代码中,从HttpResponse对象中获取响应状态码,并从HttpEntity对象中获取响应实体内容。

六、使用连接池和线程安全

以下代码示例演示如何使用连接池和线程安全的CloseableHttpClient:

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

public class HttpComponentsDemo {
    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpGet httpget = new HttpGet("http://www.example.com/");

        CloseableHttpResponse response = httpClient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                System.out.println(EntityUtils.toString(entity));
            }
        } finally {
            response.close();
        }

        httpClient.close();
    }
}

HttpClientBuilder.create().build()会创建一个线程安全、支持连接池的CloseableHttpClient实例。使用该实例发送HTTP请求,由于该实例支持连接池,所以可以重用HTTP连接以及提高性能。最后,关闭HttpClient实例释放资源。

七、使用IO处理和上传文件

以下代码示例演示如何使用HttpComponents上传文件:

import java.io.File;
import java.io.FileInputStream;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpComponentsDemo {
    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpPost httppost = new HttpPost("http://www.example.com/upload");

        File file = new File("test.txt");
        FileInputStream fis = new FileInputStream(file);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody("file", fis, ContentType.APPLICATION_OCTET_STREAM, file.getName());

        httppost.setEntity(builder.build());

        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                System.out.println(EntityUtils.toString(entity));
            }
        } finally {
            response.close();
        }

        httpclient.close();
    }
}

上述代码中,使用HttpPost对象来表示HTTP POST请求,并将要上传的文件包装到MultipartEntityBuilder对象中。最后,使用CloseableHttpClient发送HTTP请求,并将HTTP响应实体转换为字符串以打印响应内容。