打开URL 读流:
- public static String loadJson (String url) {
- StringBuilder json = new StringBuilder();
- try {
- URL urlObject = new URL(url);
- URLConnection uc = urlObject.openConnection();
- BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
- String inputLine = null;
- while ( (inputLine = in.readLine()) != null) {
- json.append(inputLine);
- }
- in.close();
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return json.toString();
- }
- public static void main(String[] args) {
- String url = "http://api.map.baidu.com/telematics/v3/weather?location=%E6%88%90%E9%83%BD&output=json&ak=rnm8udmHdWaHFWZTO2tuTiG8";
- String json = loadJson(url);
- System.out.println(json);
- }
eg:
1、将update.json部署到tomcat服务器上;
2、建立java工程;
3、新建类he.java
package json;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class he {
public static void main(String[] args) {
String url = "http://localhost:8080/update.json";
String json = loadJson(url);
System.out.println(json);
}
public static String loadJson (String url) {
StringBuilder json = new StringBuilder();
try {
URL urlObject = new URL(url);
URLConnection uc = urlObject.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String inputLine = null;
while ( (inputLine = in.readLine()) != null) {
json.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return json.toString();
}
}