URLConnection不遵循重定向
HttpURLConnection
import java.net.URL;import java.net.HttpURLConnection;import java.io.InputStream;public class Tester { public static void main(String argv[]) throws Exception{ InputStream is = null; try { String bitlyUrl = "http://bit.ly/4hW294"; URL resourceUrl = new URL(bitlyUrl); HttpURLConnection conn = (HttpURLConnection)resourceUrl.openConnection(); conn.setConnectTimeout(15000); conn.setReadTimeout(15000); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; ru; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11 (.NET CLR 3.5.30729)"); conn.connect(); is = conn.getInputStream(); String res = conn.getURL().toString(); if (res.toLowerCase().contains("bit.ly")) System.out.println("bit.ly is after resolving: "+res); } catch (Exception e) { System.out.println("error happened: "+e.toString()); } finally { if (is != null) is.close(); } }}
GET /4hW294 HTTP/1.1Host: bit.lyConnection: Keep-AliveUser-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; ru-RU; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)HTTP/1.1 301 MovedServer: nginx/0.7.42Date: Thu, 10 Dec 2009 20:28:44 GMTContent-Type: text/html; charset=utf-8Connection: keep-aliveLocation: https://www.myganocafe.com/CafeMacyMIME-Version: 1.0Content-Length: 297
res
HttpURLConnection
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><HTML><HEAD><TITLE>Moved</TITLE></HEAD><BODY><H2>Moved</H2> <A HREF="https://www.myganocafe.com/CafeMacy">The requested URL has moved here.</A><P ALIGN=RIGHT><SMALL> <I>AOLserver/4.5.1 on http://127.0.0.1:7400</I></SMALL></P></BODY></HTML>
蛊毒传说
慕码人2483693
largeQ
相关分类