1、 iframe他人的劳动成果…
好处:快
坏处:不是所有的服务提供商都支持iframe,自己无法修改样式
如: QQ天气
<iframe src="http://weather.news.qq.com/inc/ss295.htm" style="WIDTH: 212px; HEIGHT: 204px" border=0 marginWidth=0 marginHeight=0 frameBorder=no width=160 scrolling=no height=60></iframe>
中国天气网http://www.weather.com.cn
<iframesrc="http://www.weather.com.cn/static/custom/custom.html" height="193" scrolling="no" frameborder="0"></iframe>
2、 java实现方式
使用技术httpclient抓取页面方式实现,其实也挺简单,不过依懒性太强,如果他人网站做了修改,也必须做出相应修改..维护成本高
HttpClient httpClient = new HttpClient();
httpClient.getHostConfiguration().setProxy("代理主机",80); //因为我本地用的是代理
String hostUrl = "http://www.weather.com.cn/static/custom/custom.html";//抓取地址
GetMethod getMethod = new GetMethod(hostUrl);
// 使用系统提供的默认的恢复策略
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
try {
// 执行getMethod
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + getMethod.getStatusLine());
}
InputStream resStream = getMethod.getResponseBodyAsStream(); //文件较大。所以建义用流方式
BufferedReader br = new BufferedReader(new InputStreamReader(resStream));
StringBuffer resBuffer = new StringBuffer();
String resTemp = "";
while((resTemp = br.readLine()) != null){
resBuffer.append(resTemp);
}
br.close();
String response = resBuffer.toString(); //抓取的远程文件已经组织成字符串
3、 ajax+java实现方式
jquery+dom4j
实现方式相对较灵活,推荐用这种方式实现。因为ajax有跨域限制问题所以用java类做了一个代理,帮助与远程服务器通信,再把返回信息交给ajax处理
Ajax.js
$.ajax({
type: "POST",
url: "dataresource.jsp?city="+$("#city").val(),
//dataType:"xml",//此处有不解,需要返回的是xml格式,写上确出现错误…
success :function(result){
do something
},
error :function(msg){alert("e")}
})
dataresource.jsp //最好把这个功能写在单独的类
String city = request.getParameter("city");
URL url = null;
String urlStr =null;
if(city!=null)
urlStr = "http://www.google.com/ig/api?hl=zh_cn&weather="+city;
else
urlStr = "http://www.google.com/ig/api?hl=zh_cn&weather=beijing";
url = new URL(urlStr);
Properties prop = System.getProperties();
prop.put("http.proxyHost","代理主机");
prop.put("http.proxyPort","80");
InputStream in = url.openStream();
InputStreamReader isr =new InputStreamReader(in,"gbk");
SAXReader reader = new SAXReader();
Document doc = reader.read(isr);;
response.getWriter().write(doc.asXML());//返回的是xml格式