一、为什么要使用commons-httpclient?
在Java中,进行 HTTP 请求并获取返回结果是一项经常出现的任务。而Apache的commons-httpclient提供了一种简单而又可靠的方式来完成这项任务。
commons-httpclient是Apache的一个开源项目,并在许多Java框架中得到了广泛应用。与Java自带的HttpURLConnection相比,commons-httpclient提供了更多的定制和配置选项,并支持HTTP 1.0、1.1、HTTPS 协议,并且还提供了cookie管理、代理、连接池等功能。
二、获取commons-httpclient
commons-httpclient可以通过以下方式获取:
// pom.xml <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency>
// 或者下载jar包 http://archive.apache.org/dist/commons/httpclient/binaries/commons-httpclient-3.1-bin.zip
三、构建HTTP请求
1. GET请求
发送GET请求很简单,只需要构建一个GetMethod对象,并通过executeMethod方法发送请求。以下是一个示例:
import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.methods.*; public class HttpClientUtil { public static String get(String url) throws IOException { HttpClient client = new HttpClient(); GetMethod getMethod = new GetMethod(url); int statusCode = client.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { throw new RuntimeException("request failed"); } byte[] responseBody = getMethod.getResponseBody(); String response = new String(responseBody); return response; } }
这个示例使用了HttpClient类的executeMethod方法向指定的url发送了一个GET请求,并获取了响应内容。如果响应的HTTP状态码不为200,则抛出一个异常。
2. POST请求
发送POST请求稍微有些复杂,必须首先构建一个PostMethod对象,并设置其请求体。以下是一个简单的示例:
public class HttpClientUtil { public static String post(String url, String jsonBody) throws IOException { HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(url); RequestEntity requestEntity = new StringRequestEntity(jsonBody, "application/json", "UTF-8"); postMethod.setRequestEntity(requestEntity); int statusCode = client.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { throw new RuntimeException("request failed"); } byte[] responseBody = postMethod.getResponseBody(); String response = new String(responseBody); return response; } }
这个示例创建了一个PostMethod对象,并通过setRequestEntity方法设置了请求体。此示例还将请求体数据解释为JSON,并将其设置为Content-Type标头。然后使用HttpClient的executeMethod方法发送请求,并获取响应内容。
四、HTTP客户端的高级功能
1. Cookie管理
HttpClient提供了Cookie管理的功能,可以通过实例化CookieManeger对象来使用。以下示例:
import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.methods.*; public class HttpClientUtil { public static String getWithCookie(String url, String cookie) throws IOException { HttpClient client = new HttpClient(); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); GetMethod getMethod = new GetMethod(url); getMethod.setRequestHeader("Cookie", cookie); int statusCode = client.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { throw new RuntimeException("request failed"); } byte[] responseBody = getMethod.getResponseBody(); String response = new String(responseBody); return response; } }
这个示例通过实例化Client对象并设置CookiePolicy为BROWSER_COMPATIBILITY,来启用Cookie管理功能。同样,使用GetMethod类构建GET请求,并设置Cookie头来携带cookie信息。
2. 代理服务器
HttpClient还支持通过代理服务器来发送HTTP请求,以下是一个基础示例:
public class HttpClientUtil { public static String getWithProxy(String url, String proxyHost, int proxyPort) throws IOException { HttpClient client = new HttpClient(); client.getHostConfiguration().setProxy(proxyHost, proxyPort); GetMethod getMethod = new GetMethod(url); int statusCode = client.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { throw new RuntimeException("request failed"); } byte[] responseBody = getMethod.getResponseBody(); String response = new String(responseBody); return response; } }
这个示例演示了如何使用HttpClient通过代理服务器发送HTTP请求。在此示例中,我们设置了代理服务器的主机地址和端口号,然后通过HttpClient.getHostConfiguration().setProxy方法将代理服务器添加到客户端配置中。
3. 连接池
HttpClient允许开发人员构建HTTP连接池,以避免频繁创建和销毁HTTP连接。以下是一个基础示例:
import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.methods.*; public class HttpClientUtil { public static String getWithConnectionPool(String url) throws IOException { HttpClient client = new HttpClient(); client.getParams().setParameter("http.connection-manager.timeout", 1000L); MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); client.setHttpConnectionManager(connectionManager); GetMethod getMethod = new GetMethod(url); int statusCode = client.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { throw new RuntimeException("request failed"); } byte[] responseBody = getMethod.getResponseBody(); String response = new String(responseBody); return response; } }
在这个示例中,我们使用MultiThreadedHttpConnectionManager类构建了一个HTTP连接池,并通过client.setHttpConnectionManager(connectionManager)方法将其添加到HttpClient中。此外,我们还设置了最长连接时间为一秒钟。
五、总结
本文提供了使用commons-httpclient进行HTTP请求的全面指南。从构建HTTP请求到使用HTTP客户端的高级功能,我们介绍了各种使用场景,并提供了代码示例。希望这篇文章对您有所帮助!