How to process the redirect in post method using H

2019-01-15 20:54发布

问题:

In My App , I POST a xml file to the server , but sometimes the server will send back 302 and then redirect .

However , after the redirecting the method become GET , not POST, and my data in xml file can't deliver to server.

And finally the status code I got is 404.

Is there some way to process the redirect by myself ? Can I do something when the redirecting is happening?

Anyone can help? THX.!

回答1:

From RFC 2616:

If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

Are you sure your server isn't using the 'POST, redirect, GET' idiom?

You can disable automatic following of redirects in Apache HTTP client. For example:

_httpClient = new DefaultHttpClient();
_httpClient.getParams().setParameter(
    ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);


回答2:

For the record, 302's should not be treated as an instruction to perform the redirected request as a GET, that is what 303's are for. This behaviour is sloppy and the developers of HttpClient should be ashamed of themselves... :-P

I suspect your only option would be write your own, socket level implementation of an HTTP Client, that handles the redirects properly. You can have a look round the internet to see if anyone else has already produced to some code you can borrow, but if not you will have to do it yourself.

I have done this before in PHP - it's not actually that hard, HTTP is a fairly simple protocol to implement. I think cURL handles these redirects properly, if you can sub the task out to that?