Stack Overflow Asked by Luke Prior on February 3, 2021
I am trying to get the JSON file found here: https://www.reddit.com/r/arabfunny/top.json?limit=100
I have the following code:
static void getPost() throws Exception {
String webPage = "https://www.reddit.com/r/arabfunny/top.json?limit=100";
URL url = new URL(webPage);
URLConnection request = url.openConnection();
request.connect();
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonObject rootobj = root.getAsJsonObject();
}
This code throws the following error when run:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 429 for URL: https://www.reddit.com/r/arabfunny/top.json?limit=100
The problem was fixed by adding:
request.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
Answered by Luke Prior on February 3, 2021
Fix problem is set Content type to UrlConnection
request.setRequestProperty("Content-Type", "application/json; utf-8");
Full code:
package com.example;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
/**
* Hello world!
*/
public class App {
public static void main(String[] args) throws IOException {
String webPage = "https://www.reddit.com/r/arabfunny/top.json?limit=100";
URL url = new URL(webPage);
URLConnection request = url.openConnection();
request.setRequestProperty("Content-Type", "application/json; utf-8");
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonObject rootobj = root.getAsJsonObject();
System.out.println(rootobj);
}
}
Answered by sercheo_87 on February 3, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP