我在java web应用程序中使用apache http client(v4),我遇到以下情况,我需要简单的用法示例 -
(1)如何将Cookie与Apache HTTP客户端一起使用,可以使用不同的cookie选项
(2)当HTTPResponse对象中的响应可用时,提取字符集,mimetype,响应头(作为KeyValuePair)和budy(作为byte []).
我有一个包含HTTP标头的String.我想把它变成一个Apache HttpComponents HttpRequest对象.有没有办法做到这一点,而不是自己分开弦?
本教程:http://hc.apache.org/httpcomponents-core-dev/tutorial/html/fundamentals.html#d5e56和javadoc没有表明多少.
我收到客户的帖子请求.这个请求包含一些我想要在服务器端分开的json数据.我使用httpcore创建了服务器.HttpRequestHandler用于处理请求.这是我认为可行的代码
HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
InputStream inputStream = entity.getContent();
String str = inputStream.toString();
System.out.println("Post contents: " + str);*/
Run Code Online (Sandbox Code Playgroud)
但我似乎找不到使用HttpRequest对象获取请求正文的方法.如何从请求对象中提取主体?谢谢
我正在尝试从我的Android客户端发送HTTP/HTTPS发布请求.
为什么我的代码失败了?
我创建了一个apache类/ HttpClient调用.一切都很好:
HttpClient httpClient = new DefaultHttpClient();
Run Code Online (Sandbox Code Playgroud)
我已经读过这个方法已被弃用,所以我已经切换到新推荐的方法:
HttpClient httpClient = HttpClientBuilder.create().build();
Run Code Online (Sandbox Code Playgroud)
Eclipse没有这个类,所以我不得不下载Apache HttpClient 4.3.3.我通过将其复制到libs文件夹并将其添加到我的构建路径(导入的httpclient,httpclient-cache,httpcore,httpmime,fluent-hc,commons-logging,commons-codec)将其导入到我的项目中.
06-05 02:15:26.946: W/dalvikvm(29587): Link of class 'Lorg/apache/http/impl/conn/PoolingHttpClientConnectionManager;' failed
06-05 02:15:26.946: E/dalvikvm(29587): Could not find class 'org.apache.http.impl.conn.PoolingHttpClientConnectionManager', referenced from method org.apache.http.impl.client.HttpClientBuilder.build
Run Code Online (Sandbox Code Playgroud)
static private String insertJson(String json,String url){
HttpClient httpClient = HttpClientBuilder.create().build();
String responseString = "";
try {
HttpPost request = new HttpPost(url);
StringEntity params =new StringEntity(json, "UTF-8");
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity(); …Run Code Online (Sandbox Code Playgroud) 在以前的版本中,HttpClient目标主机已设置为客户端本身。在最新版本(对于HttpAsyncClient4.1.1)中,每次执行请求时,主机都设置为HttpRequest(HttpGet,HttpPost等等。)。
我想使用持久连接,所以我使用HttpAsyncClient。我这样创建和使用它:
CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start();
List<Future<HttpResponse>> responses = new ArrayList<>();
for (int i = 0; i < 10; i++)
{
HttpGet get = new HttpGet("https://google.com/");
responses.add(client.execute(get, null));
}
for (Future<HttpResponse> response : responses) {
response.get(); //wait for the response
}
Run Code Online (Sandbox Code Playgroud)
如我所测试,它的工作速度比平常更快HttpClient(如果我执行所有请求,然后等待所有响应)。
但是我无法完全了解它是如何工作的。https://google.com/建立了多少个连接?如果我使用client一台主机,然后再使用另一台主机会怎样?(正如我测试的那样,响应可以以任何顺序进行,因此我想至少有2个并行连接)。HttpAsyncClients.createDefault()和之间有什么区别HttpAsyncClients.createPipelining()?
谢谢!
java apache-httpcomponents apache-commons-httpclient apache-httpclient-4.x apache-httpasyncclient
我想知道在使用HttpClient时如何禁用特定请求的重定向.现在,我的客户端允许或禁用所有请求的重定向.我希望能够通过重定向发出一些请求,但有些请求具有重定向禁用,所有请求都使用相同的客户端.可能吗?
使用两个客户端的示例(这是我想要避免的):
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
public class MyClass {
public static void main(String[] args) throws Exception {
// Redirected client
CloseableHttpClient client = HttpClients.createDefault();
HttpGet get = new HttpGet("http://www.google.com");
client.execute(get);
// Non-redirected client
CloseableHttpClient client2 = HttpClientBuilder.create().disableRedirectHandling().build();
HttpGet get2 = new HttpGet("http://www.google.com");
client2.execute(get2);
}
}
Run Code Online (Sandbox Code Playgroud) 我正在使用 HttpClient v4.5.5
我有一个HttpClient如下:
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(totalMaxConnections);
connManager.setDefaultMaxPerRoute(defaultMaxConnPerRoute);
CloseableHttpClient httpClient =HttpClients.custom().setConnectionManager(connManager).setConnectionManagerShared(true).build();
Run Code Online (Sandbox Code Playgroud)
然后我使用 http 客户端如下:
protected Response connect(final Function<AbstractHttpAdapter, CloseableHttpResponse> pcAction) {
Response response = null;
final Instant begin = Instant.now();
try {
final CloseableHttpResponse closableResp = pcAction.apply(this);
try {
final Instant end = Instant.now();
if (closableResp != null) {
final HttpEntity responseEntity = closableResp.getEntity();
if (responseEntity != null) {
response = new Response();
InputStream is = responseEntity.getContent();
try {
final ContentType contentType = ContentType.getOrDefault(responseEntity);
Charset …Run Code Online (Sandbox Code Playgroud) 我一直在尝试使用 ResponseHandler 模拟 Apache HTTPClient,以便使用 Mockito 测试我的服务。有问题的方法是:
String response = httpClient.execute(httpGet, responseHandler);
Run Code Online (Sandbox Code Playgroud)
其中“responseHandler”是一个ResponseHandler:
ResponseHandler<String> responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK) {
return EntityUtils.toString(response.getEntity());
} else {
log.error("Accessing API returned error code: {}, reason: {}", status, response.getStatusLine().getReasonPhrase());
return "";
}
};
Run Code Online (Sandbox Code Playgroud)
有人可以建议我如何做到这一点吗?我想模拟“execute()”方法,但我不想模拟“responseHandler”(我不想测试现有的)。
谢谢!
我正在使用 Apache HTTP Components Client 4.5.7 来请求包含双斜杠的 URL。当我查看电线日志时,我看到双斜线被“固定”为只有一个斜线。不幸的是,这对我来说不是可取的行为,因为它会导致请求失败。
背景:我从 Thumbor(一个图像调整服务器)请求调整大小的图像。Thumbor URL 基本上如下所示:
这个 url 将导致拇指下载http://host.com/image.jpg并调整其大小以适应 200x200 像素。
代码如下所示:
HttpGet httpUriRequest = new HttpGet("http://thumbors-server/usafe/200x200/http://host.com/image.jpg");
CLIENT.execute(httpUriRequest, responseHandler);
Run Code Online (Sandbox Code Playgroud)
httpclient 发送到服务器的内容。然而,这是:
DEBUG o.a.h.headers http-outgoing-1 >> GET /unsafe/300x300/http:/host.com/image1.jpg HTTP/1.1
DEBUG o.a.h.headers http-outgoing-1 >> Host: localhost:4002
DEBUG o.a.h.headers http-outgoing-1 >> Connection: Keep-Alive
DEBUG o.a.h.headers http-outgoing-1 >> User-Agent: Apache-HttpClient/4.5.7 (Java/11.0.1)
DEBUG o.a.h.headers http-outgoing-1 >> Accept-Encoding: gzip,deflate
Run Code Online (Sandbox Code Playgroud)
请注意,http://host.com 被替换为http://host.com(注意缺少的第二个 /)。这将导致请求失败。
如何阻止 http 客户端“修复”我传递给它的 url?
我在项目中使用 apache HTTP Components 5.1,但遇到“SocketTimeOutException”。我无法使用以下方法来增加超时,如 Apache HTTP 客户端 4.5.13 版本中所示:org.apache.hc.client5.http.config.RequestConfig.setSocketTimeout(timeout)。
我的源代码\xe2\x86\x93
\nimport org.apache.hc.client5.http.config.RequestConfig;\nimport org.apache.hc.client5.http.impl.classic.CloseableHttpClient;\nimport org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;\nimport org.apache.hc.client5.http.impl.classic.HttpClientBuilder;\n\nRequestConfig config = RequestConfig.custom()\n .setConnectTimeout(Timeout.ofMinutes(5))\n .setConnectionRequestTimeout(Timeout.ofMinutes(5))\n .setSocketTimeout(Timeout.ofMinutes(5)).build();\nCloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore)\n .setDefaultRequestConfig(config)\n .build();\nRun Code Online (Sandbox Code Playgroud)\n错误\xe2\x86\x93
\nCaused by: java.net.SocketTimeoutException: Read timed out\nat java.base/sun.nio.ch.NioSocketImpl.timedRead(NioSocketImpl.java:283)\nat java.base/sun.nio.ch.NioSocketImpl.implRead(NioSocketImpl.java:309)\nat java.base/sun.nio.ch.NioSocketImpl.read(NioSocketImpl.java:350)\nat java.base/sun.nio.ch.NioSocketImpl$1.read(NioSocketImpl.java:803)\nat java.base/java.net.Socket$SocketInputStream.read(Socket.java:966)\nat org.apache.hc.core5.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:149)\nat org.apache.hc.core5.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:280)\nat org.apache.hc.core5.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:241)\nat org.apache.hc.core5.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:53)\nat org.apache.hc.core5.http.impl.io.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:298)\nat org.apache.hc.core5.http.impl.io.HttpRequestExecutor.execute(HttpRequestExecutor.java:175)\nat org.apache.hc.core5.http.impl.io.HttpRequestExecutor.execute(HttpRequestExecutor.java:218)\nat org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager$InternalConnectionEndpoint.execute(PoolingHttpClientConnectionManager.java:583)\nat org.apache.hc.client5.http.impl.classic.InternalExecRuntime.execute(InternalExecRuntime.java:212)\nat org.apache.hc.client5.http.impl.classic.MainClientExec.execute(MainClientExec.java:105)\nat org.apache.hc.client5.http.impl.classic.ExecChainElement.execute(ExecChainElement.java:51)\nat org.apache.hc.client5.http.impl.classic.ExecChainElement$1.proceed(ExecChainElement.java:57)\nat org.apache.hc.client5.http.impl.classic.ConnectExec.execute(ConnectExec.java:182)\nat org.apache.hc.client5.http.impl.classic.ExecChainElement.execute(ExecChainElement.java:51)\nat org.apache.hc.client5.http.impl.classic.ExecChainElement$1.proceed(ExecChainElement.java:57)\nat org.apache.hc.client5.http.impl.classic.ProtocolExec.execute(ProtocolExec.java:175)\nat org.apache.hc.client5.http.impl.classic.ExecChainElement.execute(ExecChainElement.java:51)\nat org.apache.hc.client5.http.impl.classic.ExecChainElement$1.proceed(ExecChainElement.java:57)\nat org.apache.hc.client5.http.impl.classic.HttpRequestRetryExec.execute(HttpRequestRetryExec.java:96)\nat org.apache.hc.client5.http.impl.classic.ExecChainElement.execute(ExecChainElement.java:51)\nat org.apache.hc.client5.http.impl.classic.ExecChainElement$1.proceed(ExecChainElement.java:57)\nat org.apache.hc.client5.http.impl.classic.ContentCompressionExec.execute(ContentCompressionExec.java:133)\nat org.apache.hc.client5.http.impl.classic.ExecChainElement.execute(ExecChainElement.java:51)\nat org.apache.hc.client5.http.impl.classic.ExecChainElement$1.proceed(ExecChainElement.java:57)\nat org.apache.hc.client5.http.impl.classic.RedirectExec.execute(RedirectExec.java:115)\nat org.apache.hc.client5.http.impl.classic.ExecChainElement.execute(ExecChainElement.java:51)\nat org.apache.hc.client5.http.impl.classic.InternalHttpClient.doExecute(InternalHttpClient.java:170)\nat org.apache.hc.client5.http.impl.classic.CloseableHttpClient.execute(CloseableHttpClient.java:75)\nRun Code Online (Sandbox Code Playgroud)\n