在我要地圖手機版中提供了查詢當前城市未來三天內(nèi)天氣預(yù)報的功能。天氣預(yù)報中提供了天氣情況,空氣質(zhì)量,穿衣指數(shù),洗車指數(shù)等信息。
具體的實現(xiàn)思路是,通過httpclient發(fā)送查詢請求到y(tǒng)ahoo的天氣預(yù)報接口,通過htmlparser解析返回結(jié)果,并且通過jdom包裝成一個xml返回到j(luò)2me實現(xiàn)的手機客戶端。繼而展示!
代碼如下:
MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpClient client = new HttpClient(connectionManager);
client.getHostConfiguration().setProxy("proxy******", *****);
Credentials defaultcreds = new UsernamePasswordCredentials(
"XXXXXX@****.com", "XXXXXXXXX");
client.getState().setProxyCredentials(AuthScope.ANY, defaultcreds);
outdoc = new Document();
//增加根節(jié)點
Element rootElement = new Element("handmap");
rootElement.setAttribute("version", "1.0");
HttpMethod method = new PostMethod(
"http://yahooweatherurl?city="
+ URLEncoder.encode(this.cy, "utf-8"));
client.executeMethod(method);
String result = method.getResponseBodyAsString();
System.out.println(result);
System.out.println("----------------------------");
Parser parser;
parser = new Parser(result);
parser.setEncoding("GBK");
// 尋找div的class是box2 p14的內(nèi)容
NodeFilter filter = new AndFilter(new TagNameFilter("div"),
new HasAttributeFilter("class", "box6"));
NodeList nodeList = parser.parse(filter);
parser.setInputHTML(result);
NodeFilter contentfilter = new AndFilter(new TagNameFilter("div"),
new HasAttributeFilter("class", "box7"));
NodeList contentNodeList = parser.parse(contentfilter);
NodeIterator it = nodeList.elements();
NodeIterator contentIt = contentNodeList.elements();
Node node = null;
Node contentNode = null;
StringBuffer buffer=new StringBuffer(500);
while (it.hasMoreNodes()) {
node = it.nextNode();
contentNode = contentIt.nextNode();
String nodehtml = node.toHtml();
String day = StringUtils.substringBetween(nodehtml,
"<span class=\"f18\">", "</p>");
day = day.replaceAll("</span><br />", " ");
day = day.replaceAll(" ", "");
buffer.append(day).append("\n");
//System.out.println(day);
String weather = StringUtils.substringBetween(nodehtml,
"<span class=\"f14\"><strong>", "</strong>");
weather = weather.replaceAll(" ", "");
buffer.append(weather).append("\n");
//System.out.println(weather);
String content = contentNode.toPlainTextString().replaceAll(
" ", "");
buffer.append(content).append("\n\n");
}
rootElement.setText(buffer.toString());
outdoc.setRootElement(rootElement);
} catch (UnsupportedEncodingException e) {
log.error(e.getLocalizedMessage());
} catch (MalformedURLException e) {
log.error(e.getLocalizedMessage());
} catch (IOException e) {
log.error(e);
} catch (ParserException e) {
e.printStackTrace();
}
當中需要說明的是,因為公司使用代理,所以在httpclient中我加入了代理設(shè)置:
client.getHostConfiguration().setProxy("proxy", port);
Credentials defaultcreds = new UsernamePasswordCredentials(
"XXXXXX@lingtu.com", "XXXXXXXXX");
client.getState().setProxyCredentials(AuthScope.ANY, defaultcreds);
posted on 2008-09-06 08:57
張氏兄弟 閱讀(1366)
評論(3) 編輯 收藏 所屬分類:
手機地圖