Example of getting url information after httpclient redirects
- 2020-04-01 02:58:04
- OfStack
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 {
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 an argument to the execute() method, and HttpClient stores the state information from the request-response interaction in the HttpContext
HttpResponse response = httpClient.execute(httpGet, httpContext);
//Gets the host address information after the redirect, i.e. "HTTP: arbitration.0.0.1:8088"
HttpHost targetHost = (HttpHost)httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
//Gets the URI of the actual request object, which is "/blog/admin/login.jsp" after the redirect
HttpUriRequest realRequest = (HttpUriRequest)httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
System.out.println(" The 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();
}
}
}