在使用Apache HttpClient库中的CloseableHttpClient
发送请求时,你可以通过配置RequestConfig
对象来设置正向代理。以下是一个示例代码片段来设置正向代理:
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) {
// 设置代理服务器的机和端口号
HttpHost proxy = new HttpHost("proxy.example.com", 8080);
,并设置代理
RequestConfig config = RequestConfig.custom()
.setProxy(proxy)
.build();
// 创建CloseableHttpClient,并设置RequestConfig
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultConfig(config)
.build();
try {
// 创建HttpGet请求,并设置URL
HttpGet request = new HttpGet("http://www.example.com");
// 发起请求并获取响应
CloseableHttpResponse response = httpClient.execute(request);
// 处理响应结果
System.out.println("Response Code: " + response.getStatusLine().getStatusCode());
System.out.println("Response Body: " + EntityUtils.toString(response.getEntity()));
// 关闭响应
response.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭HttpClient
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
在上述示例中,我们创建了一个HttpHost
对象来定义代理服务器的主机名和端口号。接下来,我们使用RequestConfig.custom().setProxy(proxy).build()
创建了一个包含代理设置的RequestConfig
对象。然后,我们通过使用HttpClients.custom().setDefaultRequestConfig(config).build()
构建一个带有代理设置的CloseableHttpClient
实例。
确保将proxy.example.com
和8080
替换为适当的代理服务器主机名和端口号。该示例还可以进行细化配置,如连接超时和请求超时等。在最后,通过调用httpClient.close()
关闭CloseableHttpClient
以释放相关资源。