Handling 302 Redirects in Java

I am trying to handle redirection (302) in Java code ... And the code I use is org.apache.commons.httpclient.HttpClient which does not declare setRedirectStrategy() , so I have to write my own redirect implementation:

 private void loadHttp302Request(HttpMethod method, HttpClient client, int status, String urlString) throws HttpException, IOException { if (status!=302) return; String[] url = urlString.split("/"); logger.debug("Method -> loadHttp302Request -> Location : " + method.getResponseHeader("Location") .getValue()); logger.debug("Method -> loadHttp302Request -> Cookies : " + method.getResponseHeader("Set-Cookie") .getValue()); logger.debug("Method -> loadHttp302Request -> Referrer : " + url[0]+"//"+url[2]); HttpMethod theMethod = new GetMethod(urlString+method.getResponseHeader("Location") .getValue()); theMethod.setRequestHeader("Cookie", method.getResponseHeader("Set-Cookie") .getValue()); theMethod.setRequestHeader("Referrer",url[0]+"//"+url[2]); int _status = client.executeMethod(theMethod); logger.debug("Method -> loadHttp302Request -> Status : " + _status); method = theMethod; } 

Once this is done, the status code will be 200, so it seems that everything is working, but the response body and the response stream are zero. I was able to sniff a TCP stream using wirehark and, as far as Wireshark is concerned, I return the entire response body from my redirection code ... Therefore, I am not sure what I am doing wrong or what to look for next ... Ideally It would be nice, if I could use setRedirectStrategy() , but because it is client code: p I am stuck with org.apache.commons.httpclient.HttpClient ...

I was debugging executeMethod() and found that when I read the response from the input stream, it seems to get nothing, even if wirehark certainly shows that I got the full body of the response.

Any ideas would be appreciated :)

+4
source share
1 answer

method = theMethod; at the end of loadHttp302Request there will be nothing useful. When loadHttp302Request returns, the method object pointer in your call method (java) will still point to the original HttpMethod object.

Return theMethod from loadHttp302Request and get the contents of the response instead.

+1
source

Source: https://habr.com/ru/post/1388209/


All Articles