Copy Code code as follows:
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 {
/**
* Get the URL information after redirection
* @see httpclient default automatically handles client redirection
* @see that is, after accessing page A, the assumption is redirected to the B page, then httpclient will automatically return the content of page B
* @see If you want to get the address of the B page, you need to use the HttpContext object, HttpContext is actually the client used to hold the state information in the interaction of multiple request responses.
* @see We can also use HttpContext to store some of the information we need so that we can use it to retrieve the information at the next request.
*/
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 {
Passing the HttpContext object as a parameter to the Execute () method, HttpClient stores the state information in the request response interaction in the HttpContext
HttpResponse response = Httpclient.execute (HttpGet, HttpContext);
Gets the host address information after redirection, that is, "http://127.0.0.1:8088"
Httphost targethost = (httphost) httpcontext.getattribute (executioncontext.http_target_host);
Gets the URI of the actual request object, that is, the "/blog/admin/login.jsp" after redirection
Httpurirequest realrequest = (httpurirequest) httpcontext.getattribute (executioncontext.http_request);
SYSTEM.OUT.PRINTLN ("host address:" + targethost);
SYSTEM.OUT.PRINTLN ("uri info:" + realrequest.geturi ());
httpentity entity = response.getentity ();
if (null!= entity) {
SYSTEM.OUT.PRINTLN ("Response content:" + entityutils.tostring (Entity, Contenttype.getordefault (entity). Getcharset ());
Entityutils.consume (entity);
}
catch (Exception e) {
E.printstacktrace ();
}finally{
Httpclient.getconnectionmanager (). Shutdown ();
}
}
}