Java中可以使用URL類來發送HTTP請求并獲取響應。在訪問API時,一般都會返回JSON格式的數據。下面是一個簡單的示例代碼:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; public class JsonFromUrl { public static void main(String[] args) throws IOException { String apiUrl = "https://api.com/data.json"; URL url = new URL(apiUrl); URLConnection connection = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; StringBuilder builder = new StringBuilder(); while ((line = reader.readLine()) != null) { builder.append(line); } String json = builder.toString(); System.out.println(json); } }
該代碼簡單地通過URL類打開鏈接并讀取響應。BufferedReader逐行讀取響應,并將每行數據添加到StringBuilder中。最后,將StringBuilder轉換為字符串形式的JSON響應,然后打印出來。