你这样写是看不出什么效果的,我把你的代码扩展下,
以get方式访问百度,并且抓取百度主页面html源代码
public static void main(String[] args) throws Exception
{
URL url = new URL("http://www.baidu.com.cn");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//以get方式访问百度,并将百度html页面的源码返回
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
int code = connection.getResponseCode();
if(code==200){
InputStream inputStream = connection.getInputStream();
try {
ByteArrayOutputStream bos=new ByteArrayOutputStream();
byte[] bs=new byte[1024];
while((inputStream.read(bs, 0, bs.length))!=-1){
bos.write(bs);
}
inputStream.close();
byte[] byteArray = bos.toByteArray();
String result=new String(byteArray);
System.out.println(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
不得不说,真实开发的时候这种访问服务器的耗时操作,是要开启子线程来弄的。 |