Copy the 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 will automatically handle client redirection by default
* @see that is, after accessing web page A, assuming it is redirected to web page B, then HttpClient will automatically return the content of web page B
* @see If you want to get the address of web page B, you need to use the HttpContext object. HttpContext is actually used by the client to maintain status information in multiple request and response interactions.
* @see We can also use HttpContext to store some information we need, so that we can take out this information for use during 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 {
//Pass the HttpContext object as a parameter to the execute() method, then HttpClient will store the status information during the request response interaction process in the HttpContext
HttpResponse response = httpClient.execute(httpGet, httpContext);
//Get the host address information after redirection, that is, "http://127.0.0.1:8088"
HttpHost targetHost = (HttpHost)httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
//Get the URI of the actual request object, which is "/blog/admin/login.jsp" after redirection
HttpUriRequest realRequest = (HttpUriRequest)httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
System.out.println("Host address:" + targetHost);
System.out.println("URI information:" + 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();
}
}
}