英文:
Apache Http Client execute request without sending the enclosing entity
问题
我确实有以下情景:
-
客户端通过套接字向服务器发送带有封闭实体的HTTP请求。
-
服务器将封闭实体上传到另一个位置,我们称其为存储。
我只需要实现服务器部分。
到目前为止,我能够使用Apache HTTP Components库来实现,类似于以下方式:
// 来自客户端的请求
org.apache.http.HttpRequest request = ...;
// org.apache.http.entity.InputStreamEntity将从套接字读取字节,并写入存储
HttpEntity entity = new InputStreamEntity(...);
BasicHttpEntityEnclosingRequest requestToStorage = new ......
requestToStorage.setEntity(entity);
CloseableHttpClient httpClient = ...
CloseableHttpResponse response = httpClient.execute(target, requestToStorage);
到目前为止一切都很好。问题是,存储服务器需要身份验证。当服务器进行第一次请求(通过Apache Http Client API)时,存储会响应407要求身份验证。Apache Http Client进行初始握手,然后重新发送请求,但现在没有实体,因为它已经在第一次请求中被消耗掉了。
一个解决方案是缓存来自客户端的实体,但它可能非常大,超过1GB。
问题 是否有更好的解决方案,例如预先仅发送请求的头部?
英文:
I do have the following scenario:
-
The Client sends a HTTP request with an enclosing entity to a Server, via a socket.
-
The Server uploads the enclosing entity to another location, let's call it Storage.
I am required to implement only the Server.
So far, I was able to implement it using Apache HTTP Components library using something like:
// The request from the client
org.apache.http.HttpRequest request = ...;
// The org.apache.http.entity.InputStreamEntity will
// read bytes from the socket and write to the Storage
HttpEntity entity = new InputStreamEntity(...)
BasicHttpEntityEnclosingRequest requestToStorage = new ......
requestToStorage.setEntity(entity);
CloseableHttpClient httpClient = ...
CloseableHttpResponse response = httpClient.execute(target, requestToStorage );
So far so good. Problem is, the Storage server requires authentication. When the Server makes the first request (via Apache Http Client API), the Storage responds with 407 Authentication Required. The Apache Http Client makes the initial handshake then resends the request, but now there is no entity since it has already been consumed for the first request.
One solution is to cache the entity from the Client, but it can be very big, over 1 GB.
Question Is there a better solution, like pre-sending only the request's headers?
答案1
得分: 0
使用 expect-continue
握手。
CloseableHttpClient client = HttpClients.custom()
.setDefaultRequestConfig(
RequestConfig.custom()
.setExpectContinueEnabled(true)
.build())
.build();
英文:
Use the expect-continue
handshake.
CloseableHttpClient client = HttpClients.custom()
.setDefaultRequestConfig(
RequestConfig.custom()
.setExpectContinueEnabled(true)
.build())
.build();
专注分享java语言的经验与见解,让所有开发者获益!
评论