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; }
相关文章推荐
- OSI七层和TCP/IP四层网络架构
- Android网络通信的六种方式
- php等守护进程监控脚本(转载 http://www.9958.pw/post/php_script_scan)
- 微信公众平台开发3-Https请求的封装
- Node.js创建http服务器简单实现
- 解决Xcode7 使用NSURLSession发送HTTP请求时报错问题
- Cobbler 网络自动化安装RHEL-6.5
- 加载网络数据失败的原因:
- Http协议与https协议区别
- vmware centos7 没有网络设备
- 【bzoj 2502】清理雪道(有上下界的网络流)
- 网络:XML 解析
- IOS 笔记大全 (UI控件到网络协议)
- Java使用socket网络编程实现多人聊天室
- 网络图片获取并转换为Base64字符串
- 网络:Plist 解析
- 网络:JSONKit框架的使用(天气预报)
- muduo网络库使用心得
- 神经网络研究,计算机是否能推理?
- 网络原理,以及对VMware Workstation虚拟网络VMnet0、VMnet1、VMnet8的图解