`
orc_lh
  • 浏览: 8992 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

java.net.URL的使用

阅读更多
java.net.URL的使用

以下的例子可以使用于扒取网站的数据

而在实际开发中,很多应用对java.net.URL和IO流进行封装,用返于取得函数回JSON数据;

public static void main(String args[]) throws Exception{
	String str = getContentFromURL("http://www.baidu.com");
	System.out.println(str);
}
	
private static String getContentFromURL(String urladdr) 
throws IOException {
	InputStream is=null;
	try {
		URL url=new URL(urladdr);
		URLConnection conn=url.openConnection();
		conn.setRequestProperty ("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
		is=conn.getInputStream();
		BufferedReader br=new BufferedReader(
					new InputStreamReader(is));
		StringBuilder sb=new StringBuilder();
		String str=null;
		while((str=br.readLine())!=null){
			sb.append(str+"\n");
		}
		conn.getInputStream().close();
		return sb.toString();
	}finally{
		if(is!=null){
			try {
					is.close();
			} catch (IOException e) {}
		}
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics