方法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中最常用的方法,感谢大家对移动技术网的支持。
如对本文有疑问, 点击进行留言回复!!
[杭电多校2020]第一场 1004 Distinct Sub-palindromes
Swift -- 将本地生成的UIImage进行持久化保存(存到文件中fileManager.createFile)
网友评论