简体   繁体   English

当服务器使用HttpClient-4发送错误时,中止HTTP PUT请求

[英]Abort HTTP PUT request when server sends an error with HttpClient-4

I'm using httpclient-4 to send the content of a stream (a huge file in this case) to my Tomcat's upload servlet using the following code: 我使用httpclient-4使用以下代码将流的内容(在这种情况下是一个巨大的文件)发送到我的Tomcat上传servlet:

HttpRequest httpRequest = new HttpPut(destination);
InputStreamEntity entity = new InputStreamEntity(inputStream, contentLength);
((HttpPut)httpRequest).setEntity(entity);
httpClient.execute(httpRequest,handler);

It worked fine. 它工作正常。 I later added an authentication mechanism to prevent unauthorized user to upload files. 后来我添加了一种认证机制,以防止未经授权的用户上传文件。 If someone tries to upload without being authenticated the servlet directly responds with an 如果有人试图在未经过身份验证的情况下上传,则servlet会直接响应

response.sendError(HttpServletResponse.SC_FORBIDDEN)

without even processing the request's InputStream. 甚至没有处理请求的InputStream。

The problem I am facing is that despite the fact that the request is rejected on the server side, my client keeps sending the whole content of the InputStream resulting in a completely useless network usage. 我面临的问题是,尽管请求在服务器端被拒绝,但我的客户端仍然不断发送InputStream的全部内容,从而导致完全无用的网络使用。

I have looked inside the documentation of the httpclient but unfortunately didn't find anything about this point. 我查看了httpclient的文档,但遗憾的是没有找到关于这一点的任何内容。 I have also looked on the tomcat's side to see if it's possible to abort a request but it doesn't seem possible . 我也查看了tomcat的一面,看看是否可以中止请求,但似乎不可能

Is there a way to cancel the upload of the stream in this situation? 有没有办法在这种情况下取​​消上传流?

Any insights will be appreciated. 任何见解将不胜感激。

Thanks 谢谢

A proper solution to this problem would be turning on the so called 'expect: continue' handshake on the client side. 这个问题的正确解决方案是在客户端打开所谓的'expect:continue'握手。 Newer releases of Apache HttpClient 4.x have it disabled per default. 较新版本的Apache HttpClient 4.x默认情况下禁用它。

您可以关闭服务器端的InputStream,它将停止传输。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM