---
title: "抓网页数据"
author: "danandyu8013"
date: "2012-09-07T11:14:19Z"
tags: ["HttpResult", "HttpURLConnection", "抓网页数据"]
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-08-31T10:54:02Z"
id: 1668619
url: "https://danandyu8013.iteye.com/blog/1668619"
---

抓取网页

 

 

public String getPageWeather(String weatherCode) {

String WEATHER\_ROOT = sysConf.getValue("WEATHER\_JSON");

String weatherUrl = WEATHER\_ROOT + weatherCode + ".html";

logger.info("网页抓取开始，地址 【" + weatherUrl + " 】");

String sresult = "";

/\*try {

HttpResult result = HttpUtil.getInstance().get(weatherUrl, "utf-8");

if (result.getOK()) {

logger.info("抓取成功");

sresult = result.getContent();

}

} catch (Exception e) {

e.printStackTrace();

return "";

}\*/

sresult = this.getPageContent(weatherUrl, "", 50000000);

System.out.println(sresult);

return sresult;

}

 

 

 

 

public String getPageContent(String strUrl, String strPostRequest, int maxLength) {

// 读取结果网页

StringBuffer buffer = new StringBuffer();

try {

URL newUrl = new URL(strUrl);

HttpURLConnection hConnect = (HttpURLConnection) newUrl.openConnection();

hConnect.setReadTimeout(Integer.parseInt(sysConf.getValue("TIME\_OUT")));

// POST方式的额外数据

if (strPostRequest.length() &gt; 0) {

hConnect.setDoOutput(true);

OutputStreamWriter out = new OutputStreamWriter(hConnect.getOutputStream());

out.write(strPostRequest);

out.flush();

out.close();

}

// 读取内容

 

BufferedReader rd = new BufferedReader(new InputStreamReader(hConnect.getInputStream(), "utf-8"));

int ch;

for (int length = 0; (ch = rd.read()) &gt; -1 && (maxLength &lt;= 0 || length &lt; maxLength); length++)

buffer.append((char) ch);

rd.close();

hConnect.disconnect();

return buffer.toString().trim();

} catch (Exception e) {

logger.info("对方主动关闭socket连接，放弃抓取--" );//+ e.getMessage(), e);

//e.printStackTrace();

return "";

 

}

}