gpt4 book ai didi

java - 可用的不同 HttpClient 之间有什么区别?

转载 作者:搜寻专家 更新时间:2023-10-31 19:32:09 24 4
gpt4 key购买 nike

我正在尝试编写一个简单的HttpClient 程序。这是我第一次使用 HttpClient,我很困惑要包含哪些 jars。

当我创建一个 HttpClient object 我在客户端对象中看到了不同的方法

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();
}
}
}

但是当我用谷歌搜索时,我看到了一个不同的例子,如下所示。两者有什么区别?为什么一个 HttpClient 有“execute”而另一个有“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);
}

最佳答案

HttpClient version 3 到 version 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);
}
}

首先,您可能想要创建一个连接池,以便在向同一台服务器发送多个请求时可以重用该连接。该池通常在应用程序初始化期间创建,例如作为 Spring 单例 bean。

我在这里使用了 ClosableHttpClient,因为它使用资源尝试语法,并且您需要在完成阅读后同时关闭 httpClient、响应和 inputStream。 HttpClient实际上是一个轻量级对象,socket连接和cookies等状态存储在别处。

我使用 Spring 的 MediaType.parseMediaType() 获取字符编码,并使用 Guavas CharStreams 将 inputStream 转换为字符串。在我的案例中,谷歌使用 latin-1 对内容进行了编码,因为“搜索”在丹麦语中是“søgning”。

最后一步是使用 EntityUtils.consume(entity),以确保已读取所有实体数据。如果您使用连接池,这很重要,因为未读数据会导致连接被丢弃,而不是被连接管理器重用(如果您使用 https,这非常重要)。

关于java - 可用的不同 HttpClient 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40795037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com