欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

httpclient重定向之后获取网址信息示例

程序员文章站 2024-02-21 11:54:30
复制代码 代码如下:import org.apache.http.httpentity;import org.apache.http.httphost;import org...

复制代码 代码如下:

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

上一篇: Apache Camel 1.2 Release 了

下一篇: