本文介绍了使用Java org.apache.http.client获取重定向URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在发布到服务器后,我需要帮助弄清楚如何掌握重定向.首先,我需要从服务器上获取一些cookie.然后,我使用Cookie和其他参数执行发布.然后,服务器将以302重定向进行应答.如何获取该重定向的网址?
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?
代码如下:
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);
推荐答案
请参阅我对这个问题的回答
See my answer to this question,
这篇关于使用Java org.apache.http.client获取重定向URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!