- 利用HttpURLConnection对象,我们可以从网络中获取网页数据.
- URL url = new URL("http://www.sohu.com");
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setConnectTimeout(6* 1000);//设置连接超时
- if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
- InputStream is = conn.getInputStream();//得到网络返回的输入流
- String result = readData(is, "GBK");
- conn.disconnect();
- System.out.println(result);
- //第一个参数为输入流,第二个参数为字符集编码
- public static String readData(InputStream inSream, String charsetName) throws Exception{
- ByteArrayOutputStream outStream = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = -1;
- while( (len = inSream.read(buffer)) != -1 ){
- outStream.write(buffer, 0, len);
- }
- byte[] data = outStream.toByteArray();
- outStream.close();
- inSream.close();
- return new String(data, charsetName);