我需要幫助,瞭解在向服務器發佈帖子後如何獲得重定向。 首先,我需要做一個獲取從服務器獲取一些cookie。然後我用cookies和其他參數進行發佈。服務器然後用302重定向來回答。我如何獲得重定向的網址?使用Java獲取重定向URL org.apache.http.client
代碼如下所示:
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);
這是HttpClient 3或4嗎? – skaffman 2010-01-09 14:07:10
Android中使用的一個。我不確定哪個版本。 – jakob 2010-01-09 14:53:07