public String xmlHttpPost(String requestInfo, String urlAddress, boolean isProxy,
String proxyHost, int proxyPort, ContentType contentType) {
String responseInfo = null;
InputStream inputResStream = null;
try {
CloseableHttpClient httpClient = null;
if (isProxy) {
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
httpClient = HttpClients.custom().setRoutePlanner(routePlanner).build();
}else{
httpClient = HttpClients.createDefault();
}
StringEntity stringEntity = new StringEntity(requestInfo, contentType);
HttpPost post = new HttpPost(urlAddress);
post.setEntity(stringEntity);
log.info("urlAddress: " + urlAddress.trim() + " proxyHost: " + proxyHost.trim() + " proxyPort: " + proxyPort);
CloseableHttpResponse response = httpClient.execute(post);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
inputResStream = entity.getContent();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(inputResStream));
StringBuffer resBuffer = new StringBuffer();
String resTemp = "";
while ((resTemp = br.readLine()) != null) {
resBuffer.append(resTemp);
}
responseInfo = resBuffer.toString();
} finally {
inputResStream.close();
}
}
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return responseInfo;
}
分享到:
相关推荐
1. **创建HttpClient实例**:首先需要创建一个HttpClient对象,可以选择预设的HttpClientBuilder或直接使用DefaultHttpClient。 2. **设置请求参数**:包括URL、HTTP方法(GET、POST等)、请求头、实体内容等。 3....
通过构建一个HttpClient实例,我们可以配置各种连接参数,如连接超时、重试策略等,并发起HTTP请求。 2. `HttpRequestBase`:这是一个抽象类,代表HTTP请求的基本实现,如HttpGet、HttpPost等。开发者可以根据需求...
- **线程安全**:HttpClient实例不是线程安全的,如果在多线程环境中使用,需要为每个线程创建单独的实例或者使用线程局部变量。 Apache HttpClient 4.3.5作为一款强大的HTTP客户端工具,不仅提供了丰富的功能,...
在使用过程中,了解如何创建HttpClient实例,设置请求头,处理响应,以及如何正确关闭资源是非常重要的。 例如,一个简单的GET请求可能如下所示: ```java CloseableHttpClient httpClient = HttpClients.create...
6. 执行请求:通过`httpClient.execute(httpPost)`发送请求并获取响应。 7. 处理响应:检查响应状态码,获取响应实体并进行后续处理。 8. 关闭资源:使用`httpClient.close()`关闭连接。 文件上传是Web开发中的...
在实际使用中,开发者首先需要将这三个JAR文件添加到项目的类路径中,然后可以通过HttpClient的相关API来构建HTTP请求,例如创建`CloseableHttpClient`实例,定义`HttpGet`或`HttpPost`对象,并设置必要的请求头和...
- 它允许开发者轻松地发送HTTP请求,并处理来自服务器的响应。 - **使用HttpClient发起HTTP请求**: - 通过引入HttpClient依赖,可以在Java代码中模拟HTTP请求,获取响应数据。 - 常见应用场景包括数据抓取...