1. 程式人生 > >HttpClient獲取重定向之後的網址資訊

HttpClient獲取重定向之後的網址資訊

package com.jadyer.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

public class HttpClientDemo {
	/**
	 * 獲取重定向之後的網址資訊
	 * @see HttpClient預設會自動處理客戶端重定向
	 * @see 即訪問網頁A後,假設被重定向到了B網頁,那麼HttpClient將自動返回B網頁的內容
	 * @see 若想取得B網頁的地址,就需要藉助HttpContext物件,HttpContext實際上是客戶端用來在多次請求響應的互動中,保持狀態資訊的
	 * @see 我們自己也可以利用HttpContext來存放一些我們需要的資訊,以便下次請求的時候能夠取出這些資訊來使用
	 */
	public static void getRedirectInfo(){
		HttpClient httpClient = new DefaultHttpClient();
		HttpContext httpContext = new BasicHttpContext();
		HttpGet httpGet = new HttpGet("http://127.0.0.1:8088/blog/main.jsp");
		try {
			//將HttpContext物件作為引數傳給execute()方法,則HttpClient會把請求響應互動過程中的狀態資訊儲存在HttpContext中
			HttpResponse response = httpClient.execute(httpGet, httpContext);
			//獲取重定向之後的主機地址資訊,即"http://127.0.0.1:8088"
			HttpHost targetHost = (HttpHost)httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
			//獲取實際的請求物件的URI,即重定向之後的"/blog/admin/login.jsp"
			HttpUriRequest realRequest = (HttpUriRequest)httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
			System.out.println("主機地址:" + targetHost);
			System.out.println("URI資訊:" + realRequest.getURI());
			HttpEntity entity = response.getEntity();
			if(null != entity){
				System.out.println("響應內容:" + EntityUtils.toString(entity, ContentType.getOrDefault(entity).getCharset()));
				EntityUtils.consume(entity);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			httpClient.getConnectionManager().shutdown();
		}
	}
}