(1)定义路径URL对象
(2)打开连接
(3)设置连接时长、连接方法(GET/POST)
(4)获取输入流
(5)解析转化为需要内容
通过xml从网络中获取网页数据:
public String getContent(String url) throws Exception{
URL url = new URL("http://www.sohu.com"); //定义路径URL对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //打开连接
conn.setConnectTimeout(5* 1000); //设置连接超时
conn.setRequestMethod(“GET”); //以get方式发起请求
if (conn.getResponseCode() != 200)
throw new RuntimeException("请求url失败");
InputStream is = conn.getInputStream(); //得到网络返回的输入流
String result = readData(is, "GBK"); //解析获取字符串
conn.disconnect();
return 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);
}
通过JSON从网络中获取网页数据:
JSON格式:[{name:"conghua",age:20},{name:"weicong",age:21}]
public List<Person> getJSONPerson(String path) throws Exception{
List<Person> persons = new ArrayList<Person>() ;
URL url = new URL(path) ;
HttpURLConnection conn = (HttpURLConnection)url.openConnection() ;
conn.setConnectTimeOut(5*1000) ;
conn.setRequestMethod("GET") ;
InputStream is = url.getInputStream() ;
String json = StreamTool.readInputStream(is) ;
JSONArray array = new JSONArray(json) ;
for(int i=0; i<array.length(); i++){
JSONObject item = array.getJSONObject(i) ;
Person person = new Person(item.getString("name"),item.getInt(age)) ;
persons.add(person) ;
}
return persons ;
}
利用HttpURLConnection对象,我们可以从网络中获取文件数据.
URL url = new URL("http://photocdn.sohu.com/20100125/Img269812337.jpg");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5* 1000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200)
throw new RuntimeException("请求url失败");
InputStream is = conn.getInputStream();
readAsFile(is, "Img269812337.jpg");
public static void readAsFile(InputStream inSream, File file) throws Exception{
FileOutputStream outStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = -1;
while( (len = inSream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
outStream.close();
inSream.close();
}