[英]how i get JSON as string from url (java)
我想將此JSON保存在url { https://www.instagram.com/ihanan95/?__a=1 }中,並通過java將其保存為字符串,我嘗試使用所有建議,但何時得到空字符串。
您可以使用Spring的 RestTemplate
以String
獲取響應,例如:
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("https://www.instagram.com/ihanan95/?__a=1", String.class);
System.out.println(response);
如果不允許使用第三方庫,則可以使用URLConnection
進行相同操作,例如:
URLConnection connection = new URL("https://www.instagram.com/ihanan95/?__a=1").openConnection();
try(Scanner scanner = new Scanner(connection.getInputStream());){
String response = scanner.useDelimiter("\\A").next();
System.out.println(response);
}
從遠程網站讀取JSON文件。
例:
URL url = new URL("https://www.instagram.com/ihanan95/?__a=1");
JSONTokener tokener = new JSONTokener(url.openStream());
JSONObject obj = new JSONObject(tokener);
JSONObject data = obj.getJSONObject("user");
String message = data.getString("message");
JSONTokener 文檔
依賴
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.