网络爬虫,HttpURLConnection连接重置问题!

idea_sh 2014-03-12 09:46:12
/**
* 根据 url 获得源码
*
* @param 网页地址
* @return 源码字符串
*/
public static String GetHtmlByUrl(String htmlUrl) {
htmlCode.setLength(0);
URL url = null;
HttpURLConnection conn = null;
BufferedReader br = null;
InputStreamReader isr = null;
InputStream is = null;
int responseCode;
String readerLine = "";

try {
url = new URL(htmlUrl);
conn = (HttpURLConnection) url.openConnection();
simulationBrowser(conn);// 模拟浏览器

responseCode = conn.getResponseCode();
// TODO:如果得到返回html代码,则读取
if (responseCode == 200) {
is = conn.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
while ((readerLine = br.readLine()) != null) {
htmlCode.append(readerLine);
}
} else {
System.out.println(WebSpiderConstant.responseStrError
+ responseCode);
}
return htmlCode.toString();
} catch (Exception e) {
WebSpiderConstant.RETRY_COUNT++;
System.out.println(WebSpiderConstant.connStrError
+ WebSpiderConstant.RETRY_COUNT);
if (WebSpiderConstant.RETRY_COUNT < WebSpiderConstant.RETRY_COUNT_BREAK) {
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
System.err.println(WebSpiderConstant.EXCEPTION_ROLLBACK
+ e1.getMessage());
e1.printStackTrace();
}

return GetHtmlByUrl(htmlUrl);
} else {
System.out.println(WebSpiderConstant.ERROR_HTTPCONNECTION);
}
} finally {

try {
if (br != null) {
br.close();
br = null;
}
if (isr != null) {
isr.close();
isr = null;
}
if (is != null) {
is.close();
is = null;
}

} catch (IOException e) {
System.out.println(WebSpiderConstant.ERROR_CLOSEIO);
e.printStackTrace();
}
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return htmlCode.toString();
}
...全文
504 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
tony4geek 2014-03-12
  • 打赏
  • 举报
回复
是不是没读完你重置了。/
idea_sh 2014-03-12
  • 打赏
  • 举报
回复
等答案,等答案
idea_sh 2014-03-12
  • 打赏
  • 举报
回复
获取页面源代码,为了防止 连接失败,所以加了判断,如果出现异常,就再去调用这个方法,然后返回值。这样写有没有问题?但总是出现 java.net.SocketException: Connection reset ,敬请高人指点!

81,122

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧