Get hold of redirect url with Java org.apache.http.client

httpclient, java, post, redirect

Solution

See my answer to this question,

HttpClient 4 - how to capture last redirect URL

Problem

I need help with figuring out how to get hold of the redirect after I make a post to the server. First, I need to do a get to obtain some cookies from the server. Then I perform a post with the cookies and additional parameters. The server then answers with a 302 redirect. How do I get the url for that redirect? Code looks like follows: ``` HttpGet get = new HttpGet(urlOne); try { //Creating a local instance of cookie store. CookieStore cookieJar = new BasicCookieStore(); // Creating a local HTTP context HttpContext localContext = new BasicHttpContext(); // Bind custom cookie store to the local context localContext.setAttribute(ClientContext.COOKIE_STORE, cookieJar); HttpResponse response = httpClient.execute(get, localContext); HttpEntity entity = response.getEntity(); System.out.println("------------------GET----------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } // Print out cookies obtained from server List<Cookie> cookies = cookieJar.getCookies(); for (int i = 0; i < cookies.size(); i++) { System.out.println("Local cookie: " + cookies.get(i)); } if (entity != null) { entity.consumeContent(); } System.out.println("------------------GET-END---------------------"); // Create a new post HttpPost post = new HttpPost(urlTwo); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); // Add params HttpParams params = new BasicHttpParams(); params.setParameter("action", "search"); params.setParameter("word", "hello"); post.setParams(params); //Execute HttpResponse response2 = httpClient.execute(post, localContext); ```

Original source

Related problems