本文主要是介绍HttpURLConnection获取url 302地址,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
有时候需要从访问的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; }
这篇关于HttpURLConnection获取url 302地址的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!