qq_37521752
wxmmmmmmm
2017-10-16 08:58

HttpURLConnection的301永久重定向问题,希望大神帮忙一下

  • 网络

源码 -- 爬取工具类

public static String getHtmlUrl(String address){
//http://www.cnblogs.com/fangg/p/5886233.html 打开链接
HttpURLConnection conn = null;
//http://www.cnblogs.com/blackiesong/p/6182038.html 通过网络或远程链接达到目的
URL url = null;
//输入流
InputStream in = null;
//缓冲流
BufferedReader reader = null;
//存储和操作字符串
StringBuffer stringBuffer = null;
try {
//代表一个绝对地址,URL对象直接指向这个资源
url = new URL(address);
//打开链接
conn = (HttpURLConnection) url.openConnection();
//设置链接超时时间
conn.setConnectTimeout(5000);
//设置读取超时时间
conn.setReadTimeout(5000);
//设置是否向httpUrlConnection输出,post请求,参数要放置在http正文中,需要设置为true,默认为false
//conn.setDoInput(true);
//解决301永久重定向问题
conn.setInstanceFollowRedirects(false);
//建立连接,并不会向服务器传送数据
conn.connect();
in = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
stringBuffer = new StringBuffer();
String line = null;
while((line = reader.readLine()) != null){
stringBuffer.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
conn.disconnect();
try {
in.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}

    return stringBuffer.toString();
}
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答