Java 获取网络302重定向URL的方法
程序员文章站
2022-06-08 23:02:12
方法1:
import java.net.httpurlconnection;
import java.net.url;
import org.juni...
方法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中最常用的方法,感谢大家对的支持。
上一篇: 口碑营销通常通过哪些渠道进行营销?