httpclient重定向以後獲得網址信息示例。本站提示廣大學習愛好者:(httpclient重定向以後獲得網址信息示例)文章只能為提供參考,不一定能成為您想要的結果。以下是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();
}
}
}