Reputation: 371
I'm currently trying to access a web API (not mine) located under https://fnbr.co/api/shop.
The code I am running is basically this:
URL url = new URL("https://fnbr.co/api/shop");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.flush();
System.out.println(conn.getResponseCode()); // second error
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream())); // first error
// read from this reader
Console output (the response code) is
404
FileNotFoundException: https://fnbr.co/api/shop
at the line with conn.getInputStream()
and an another
FileNotFoundException: https://fnbr.co/api/shop
in the line with conn.getResponseCode()
Where is my problem (because 404 should mean that the file doesn't exist, but I can access it via my browser)?
Upvotes: 0
Views: 268
Reputation: 41997
conn.setDoOutput(true);
and
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.flush();
This looks bogus for a GET request.
Upvotes: 0
Reputation: 22646
HTTP 404 means that the requested URL does not exist. That means in your case that there is nothing behind GET https://fnbr.co/api/shop address. Maybe you need to use different protocol like PUT, POST, etc.:
404 Not Found The requested resource could not be found but may be available in the future. Subsequent requests by the client are permissible.
Here is the official description of the HTTP response codes.
You need to handle errors in your client code, like HTTP 404 so you can read the response (keep in mind that it is not file, it is a request-response!) if you get back HTTP 200, like this:
if (conn.getResponseCode() == 200) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
}
Upvotes: 1