代碼如下:
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();
}
}
}