Getting URL after redirect using HttpClient.Execute (HttpGet)

I have been looking for some time, and I do not find a clear answer. I am trying to login to webstie. https://hrlink.healthnet.com/ This website redirects to a login page, which is optional. I have to publish my credentials for the redirected URL.

I am trying to encode this in Java, but I do not understand how to get the URL from the response. It may look a little dirty, but I have it while I'm testing.

HttpGet httpget = new HttpGet("https://hrlink.healthnet.com/"); HttpResponse response = httpclient.execute(httpget);HttpEntity entity = response.getEntity(); String redirectURL = ""; for(org.apache.http.Header header : response.getHeaders("Location")) { redirectURL += "Location: " + header.getValue()) + "\r\n"; } InputStream is; is = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); String result = sb.toString(); 

I know that they redirect me because my result line shows the actual login page, but I can’t get the new URL.

In FireFox, I am using TamperData. When I go to this website https://hrlink.healthnet.com/ , I have a GET with 302 - Found and Location of the Login. Then another GET to the actual login page

Any help gratefully thanks you.

+6
source share
1 answer

Check out the w3c documentation :

10.3.3 302 Found

The temporary URI MUST be indicated by the Location field in the response. If the request method was not HEAD, the response object SHOULD contain a short hypertext note with a hyperlink to the new URI (s).

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

One solution is to use the POST method to interrupt automatic client-side redirection:

 HttpPost request1 = new HttpPost("https://hrlink.healthnet.com/"); HttpResponse response1 = httpclient.execute(request1); // expect a 302 response. if (response1.getStatusLine().getStatusCode() == 302) { String redirectURL = response1.getFirstHeader("Location").getValue(); // no auto-redirecting at client side, need manual send the request. HttpGet request2 = new HttpGet(redirectURL); HttpResponse response2 = httpclient.execute(request2); ... ... } 

Hope this helps.

+8
source

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


All Articles