[英]how i get JSON as string from url (java)
我想将此JSON保存在url { https://www.instagram.com/ihanan95/?__a=1 }中,并通过java将其保存为字符串,我尝试使用所有建议,但何时得到空字符串。
You can use Spring's RestTemplate
to get the response as String
, eg: 您可以使用Spring的 RestTemplate
以String
获取响应,例如:
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("https://www.instagram.com/ihanan95/?__a=1", String.class);
System.out.println(response);
If you are not allowed to use third party libaries then you can do the same with URLConnection
, eg: 如果不允许使用第三方库,则可以使用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);
}
Read JSON file from remote website. 从远程网站读取JSON文件。
Example: 例:
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 Doc JSONTokener 文档
Dependencies 依赖
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.