1、请求获取链接
1.1 URL.openConnection()
返回一个URLConnection对象,他表示URL所引用的远程对象的链接。
1.2 URL.openStream()
返回URL链接读入的输入流,打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream
可能形式为:openConnection().getInputStream()
2、获取数据
2.1 获取网页、文字
StringBuffer sb = new StringBuffer("");
URL url;
try {
url = new URL(targetUrl);
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
String s = "";
while ((s = br.readLine()) != null) {
i++;
sb.append(s + "\r\n");
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(sb.toString()); 2.2 获取文件
2.2.1 保存文件的格式
打开谷歌的开发者工具,进入network选项,并在地址栏输入所需网址便可查找到如下图:
2.2.2 保存文件
URL url; url = new URL(targetUrl);
File gzipFile = new File("weather.gzip");
FileOutputStream fos = new FileOutputStream(gzipFile );
DataInputStream dis = new DataInputStream(url.openStream());
byte[]bytes = new byte[1024];
int length = 0;
while((length = dis.read(bytes,0,bytes.length)) != -1) {
fos.write(bytes,0,length);
fos.flush();
}
fos.close(); //解压并删除该文件
GZipUtils.decompress(gzipFile , true);
fixedFileName("weatherip","weather.json");
return new File("weather.json"); 
京公网安备 11010502036488号