I've read this post on how to do a POST request in Java. I don't understand how I can implement this in a JSON parser. This is what I tried so far:
public class JSONParser {
private String read(BufferedReader bufferedReader) throws IOException {
//Creates new StringBuilder to avoid escaping chars
StringBuilder stringBuilder = new StringBuilder();
//Gets the currentLine
String currentLine;
while((currentLine = bufferedReader.readLine()) !=null ){
//Adds the currentLine to the stringBuild if the currentLine is not null
stringBuilder.append(currentLine);
}
//Returns the StringBuilder is String format
return stringBuilder.toString();
}
public JSONObject readJsonFromUrl(String JSONurl) throws IOException, JSONException {
InputStream url = new URL(JSONurl).openStream();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url));
String jsonText = read(bufferedReader);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
url.close();
}
}
public void printJSON() throws IOException, JSONException {
JSONObject json = readJsonFromUrl("http://grwn.ddns.net:1337/locations");
System.out.print(json);
//for (Integer i = 0; i < json.getJSONArray("damage_or_theft_car").length(); i++) {
// System.out.println(json.getJSONArray("damage_or_theft_car")
//.getJSONObject(i).get("hood_id"));
//}
}
}
When I run this code with a link which doesn't require a POST request it all works fine but when I run this code on a link which DOES require a POST request I get the following error:
Exception in thread "main" java.io.FileNotFoundException: http://grwn.ddns.net:1337/locations
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1872)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at java.net.URL.openStream(URL.java:1045)
at com.company.JSONParser.readJsonFromUrl(JSONParser.java:30)
at com.company.JSONParser.printJSON(JSONParser.java:42)
at com.company.Main.main(Main.java:33)
Could someone help me out or point me in the right direction?