/**
*
*/
package com.duoguo.url;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* @author shyboy(chao.shen@duoguo.cn)
*
*/
public class URLClient {
StringBuilder sb = new StringBuilder();
/**
* 连接到服务器,并请求给定的文档
*
* @param urlString
* :文档地址
* @return:String
*/
public String getDocumentAt(String urlString) {
try {
URL url = new URL(urlString);// 生成url对象
URLConnection urlConnection = url.openConnection();// 打开url连接
BufferedReader br = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
} catch (MalformedURLException e) {
System.out.println("不能连接到URL:" + urlString);
e.printStackTrace();
} catch (IOException e) {
System.out.println("连接到URL抛出异常信息:" + urlString);
e.printStackTrace();
}
return sb.toString();
}
/**
* @param args
*/
public static void main(String[] args) {
URLClient client = new URLClient();
String url = client.getDocumentAt("http://www.baidu.com");
System.out.println(url);
}
}