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();
}
}
}