当前位置: 移动技术网 > IT编程>开发语言>Java > Java 获取网络302重定向URL的方法

Java 获取网络302重定向URL的方法

2019年09月06日  | 移动技术网IT编程  | 我要评论

方法1:

import java.net.httpurlconnection;
import java.net.url;
 
import org.junit.assert;
import org.junit.test;
 
public class getredirecturltest {
  @test
  public void test_getredirecturl() throws exception {
    string url="http://www.baidu.com/link?url=bybjlphsj5nxx6desxbmmjiru5w4eh0yg5wcqpe3kcqmljk_rjbmdeygm0ddtcotdgaz7rh80gxjvtvoqjuyxk";
    string expecturl="http://www.zhihu.com/question/20583607/answer/16597802";
    string redicturl = getredirecturl(url);
    assert.assertequals(expecturl, redicturl);
  }
  
  /**
   * 获取重定向地址
   * @param path
   * @return
   * @throws exception
   */
  private string getredirecturl(string path) throws exception {
    httpurlconnection conn = (httpurlconnection) new url(path)
        .openconnection();
    conn.setinstancefollowredirects(false);
    conn.setconnecttimeout(5000);
    return conn.getheaderfield("location");
  }
}

方法2:

/**
   * 处理跳转链接,获取重定向地址
   * @param url  源地址
   * @return   目标网页的绝对地址
   */
  public string getabsurl(string url){
    closeablehttpclient httpclient = httpclients.createdefault();
    httpclientcontext context = httpclientcontext.create();
    httpget httpget = new httpget(url);
    closeablehttpresponse response = null;
    string absurl = null;
    try {
      response = httpclient.execute(httpget, context);
      httphost target = context.gettargethost();
      list<uri> redirectlocations = context.getredirectlocations();
      uri location = uriutils.resolve(httpget.geturi(), target, redirectlocations);
      system.out.println("final http location: " + location.toasciistring());
      absurl = location.toasciistring();     
    }catch(ioexception e){
      e.printstacktrace();
    }catch (urisyntaxexception e) {     
      e.printstacktrace();
    }finally {
      try {
        httpclient.close();
        response.close();
      } catch (ioexception e) {        
        e.printstacktrace();
      }
    }
    return absurl;
  }

以上就是2中最常用的方法,感谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网