Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

response.sendError(HttpServletResponse.SC_FORBIDDEN)

without even processing the request's 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.

I have looked inside the documentation of the httpclient but unfortunately didn't find anything about this point. 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.

Is there a way to cancel the upload of the stream in this situation?

Any insights will be appreciated.

Thanks

like image 313
Davz Avatar asked Apr 20 '26 08:04

Davz


1 Answers

A proper solution to this problem would be turning on the so called 'expect: continue' handshake on the client side. Newer releases of Apache HttpClient 4.x have it disabled per default.

like image 142
ok2c Avatar answered Apr 21 '26 21:04

ok2c



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!