您的位置:首页 > 理论基础 > 计算机网络

HttpURLConnection获取url 302地址

2016-04-07 16:57 543 查看
有时候需要从访问的url地址中取出302地址,自己做处理(当然,是针对一次重定向)

public void onStartTest() {

new Thread(new Runnable() {
@Override
public void run() {
test302();
}
}).start();
}

private void test302() {
String strUrl = "http://www.sogou.com";
try {
HttpURLConnection urlConnection = getConnection(strUrl);
urlConnection.connect();
if (urlConnection.getResponseCode() == 302) {
String url302 = urlConnection.getHeaderField("Location");
if (TextUtils.isEmpty(url302)) {
url302 = urlConnection.getHeaderField("location"); //临时重定向和永久重定向location的大小写有区分
}
if (!(url302.startsWith("http://") || url302.startsWith("https://"))) { //某些时候会省略host,只返回后面的path,所以需要补全url
URL originalUrl = new URL(strUrl);
url302 = originalUrl.getProtocol() + "://" + originalUrl.getHost() + ":" + originalUrl.getPort() + url302;
}
if (mCallback != null) {
mCallback.callback(url302);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 获取GET连接
*
* @param strUrl 连接的地址
* @return 连接对象
* @throws IOException
*/
private HttpURLConnection getConnection(String strUrl) throws IOException {
URL url = new URL(strUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setUseCaches(false);
httpURLConnection.setInstanceFollowRedirects(false); //设置成false,则需要自己从http reply中分析新的url自己重新连接。
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.setReadTimeout(10000);
return httpURLConnection;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: