我正在尝试编写一个简单的HttpClient程序.这是我第一次与之合作HttpClient,我很困惑要包括哪些罐子.
当我创建一个对象时,我已经包含了apache-httpcomponents-httpclient.jar和 org.apache.commons.httpclient.jar这些,我HttpClient在客户端对象中看到了不同的方法
package com.comverse.rht;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
public class HttpClientTest {
public static void main(String[] args) throws URIException {
URI url = new URI("http://www.google.com/search?q=httpClient");
HttpClient client = new HttpClient();
GetMethod get = new GetMethod();
PostMethod post = new PostMethod();
String responseString;
StringBuilder sb = new StringBuilder();
String line;
// add request header
get.setURI(url);
get.addRequestHeader("User-Agent", "shaiksha429");
try {
int respCode = client.executeMethod(get);
System.out.println("Response Code:" +respCode);
System.out.println(
"PCRF HTTP Status" + HttpStatus.getStatusText(respCode)
);
responseString = get.getResponseBodyAsString();
BufferedReader rd = null;
rd = new BufferedReader(
new InputStreamReader(get.getResponseBodyAsStream())
);
while ((line = rd.readLine()) != null) {
sb.append(line + '\n');
}
System.out.println(sb);
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我谷歌时,我看到了一个不同的例子,如下所示.两者有什么区别?为什么一个HttpClient人"执行"而另一个人拥有" executeMethod".我需要使用哪一个?
String url = "http://www.google.com/search?q=httpClient";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent())
);
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
Run Code Online (Sandbox Code Playgroud)
从HttpClient版本3到版本4有很多变化.第二个例子肯定来自HttpClient 4,所以第一个例子可能来自之前的版本.
这是将进行谷歌搜索的代码,并将结果读入字符串
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(60);
connectionManager.setDefaultMaxPerRoute(6);
try (CloseableHttpClient client = HttpClients.custom().setConnectionManager(connectionManager).build()) {
HttpGet request = new HttpGet("http://www.google.com/search?q=httpClient");
request.setHeader("User-Agent", "HttpClient");
try (CloseableHttpResponse response = client.execute(request)) {
MediaType mediaType = MediaType.parseMediaType(response.getFirstHeader("Content-Type").getValue());
Charset charSet = mediaType.getCharSet();
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
String body = CharStreams.toString(new InputStreamReader(is, charSet));
System.out.println("body = " + body);
EntityUtils.consume(entity);
}
}
Run Code Online (Sandbox Code Playgroud)
首先,您可能想要创建连接池,因此如果向同一服务器发送多个请求,则可以重用连接.该池通常在应用程序初始化期间创建,例如作为Spring单例bean.
在这里,我使用了ClosableHttpClient,因为它使用了资源尝试语法,并且在阅读完毕后需要关闭httpClient,响应和inputStream.HttpClient实际上是一个轻量级对象,状态如套接字连接和cookie存储在别处.
我使用Spring的MediaType.parseMediaType()来获取char编码,使用Guavas CharStreams将inputStream转换为String.在我的情况下,谷歌使用latin-1编码内容,因为"搜索"在丹麦语中是"søgning".
最后一步是使用EntityUtils.consume(entity),以确保已读取所有实体数据.如果使用连接池,这很重要,因为未读数据将导致连接被丢弃,而不是被连接管理器重用(如果您使用https,这非常重要).
| 归档时间: |
|
| 查看次数: |
1099 次 |
| 最近记录: |