java通过URL读取json数据

打开URL  读流:

  1. public static String loadJson (String url) {  
  2.         StringBuilder json = new StringBuilder();  
  3.         try {  
  4.             URL urlObject = new URL(url);  
  5.             URLConnection uc = urlObject.openConnection();  
  6.             BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));  
  7.             String inputLine = null;  
  8.             while ( (inputLine = in.readLine()) != null) {  
  9.                 json.append(inputLine);  
  10.             }  
  11.             in.close();  
  12.         } catch (MalformedURLException e) {  
  13.             e.printStackTrace();  
  14.         } catch (IOException e) {  
  15.             e.printStackTrace();  
  16.         }  
  17.         return json.toString();  
  18.     }  
main方法测试:
  1. public static void main(String[] args) {  
  2.         String url = "http://api.map.baidu.com/telematics/v3/weather?location=%E6%88%90%E9%83%BD&output=json&ak=rnm8udmHdWaHFWZTO2tuTiG8";   
  3.         String json = loadJson(url);  
  4.         System.out.println(json);  
  5.     } 


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();  
}  
}






猜你喜欢

转载自blog.csdn.net/qq_28938403/article/details/51506637