根据url获取网页内容

 

PrintWriter out = null;
out = response.getWriter();
try{

URL getUrl = new URL("http://www.kuaidi100.com/applyurl?key="+KEY+"&com="+com+"&nu="+nu);
//System.out.println("getUrl:"+getUrl);
// 根据拼凑的URL,打开连接,URL.openConnection函数会根据URL的类型,
// 返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) getUrl
.openConnection();
// 进行连接,但是实际上get request要在下一句的connection.getInputStream()函数中才会真正发到
// 服务器
connection.connect();
// 取得输入流,并使用Reader读取
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));//设置编码,否则中文乱码
String lines;
while ((lines = reader.readLine()) != null){
//lines = new String(lines.getBytes(), "utf-8");
out.print(lines);//输出网页内容
}
reader.close();
// 断开连接
connection.disconnect();
}catch(Exception e){
e.printStackTrace();
}finally {
out.close();
}

 

posted on 2013-11-27 11:30  nancyxia  阅读(340)  评论(0)    收藏  举报