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






### 回答1: Java可以使用HttpURLConnection或者HttpClient来请求HTTP获取JSON数据。 使用HttpURLConnection: ```java import java.net.HttpURLConnection; import java.net.URL; import java.io.BufferedReader; import java.io.InputStreamReader; public class HttpUrlConnectionExample { public static void main(String[] args) { try { URL url = new URL("http://example.com/api/data.json"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 使用HttpClient: ```java import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class HttpClientExample { public static void main(String[] args) { try { HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet("http://example.com/api/data.json"); request.addHeader("Accept", "application/json"); HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } String json = EntityUtils.toString(response.getEntity()); System.out.println(json); } catch (Exception e) { e.printStackTrace(); } } } ``` ### 回答2: Java请求HTTP获取JSON数据可以通过以下几个步骤实现: 第一步,导入相关依赖。Java中访问HTTP资源需要使用到Java标准库中的HttpURLConnection,同时需要使用到JSON类库,例如Gson或者Jackson等。 第二步,编写Java代码向服务器发起HTTP请求。这个过程需要指定请求的URL、请求方法(GET、POST等)、设置请求头、设置请求参数等。例如: ``` URL url = new URL("http://example.com/api/data.json"); HttpURLConnection con = (HttpURLConnection)url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", "Mozilla/5.0"); int responseCode = con.getResponseCode(); ``` 第三步,判断HTTP请求的返回状态是否为200。如果返回状态为200,表示请求成功,可以接收服务器返回的数据。例如: ``` if(responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); String jsonStr = response.toString(); } ``` 第四步,对返回的数据进行解析。如果使用Gson库,可以很方便地将JSON字符串转换为Java对象。例如: ``` Gson gson = new Gson(); DataObject data = gson.fromJson(jsonStr, DataObject.class); ``` 其中,DataObject是自定义的Java对象,用于表示JSON数据中的各个字段。通过上述步骤,就可以实现Java请求HTTP获取JSON数据的功能。 ### 回答3: Java是一种强大的编程语言,可以通过它来请求HTTP获取JSON数据。方式有以下几种: 1. 使用第三方库 在Java中,我们可以使用一些第三方库来获取JSON数据,并将其转换成Java对象。例如,我们可以使用Apache HttpClient或OkHttp来发送HTTP请求并获取响应。同时,我们可以使用Gson、Jackson或Fastjson等库,将JSON数据解析成Java对象。这些库提供了许多工具和 API 来完成请求和解析的流程,简化了开发者的工作。 比如,使用OkHttp发送请求并解析响应: ``` OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("http://example.com/api/data") .build(); Response response = client.newCall(request).execute(); String json = response.body().string(); Gson gson = new Gson(); MyData myData = gson.fromJson(json, MyData.class); ``` 2. 使用Java内置的库 Java中还提供了一些内置的API和类,在一定程度上也可以进行请求和解析。例如,使用HttpURLConnectionURL类来发送HTTP请求,然后将其转换成JSON,使用标准库JSON提取数据。这种方式虽然比较原始,但是对于一些简单的请求和解析场景,非常实用。 比如,使用HttpURLConnection发送请求并解析响应: ``` URL url = new URL("http://example.com/api/data"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONObject json = new JSONObject(response.toString()); String data = json.getString("data"); ``` 无论使用哪种方式,都需要注意异常处理和线程安全等问题。同时,开发者还需了解如何处理无效和异常的响应和JSON数据,确保应用程序的正常运行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值