Search code examples
javagetimgur

Imgur API request using Java returns 400 status


I am trying to send a GET request to the Imgur API to upload an image.

When I use the following code I receive a 400 status response from the Imgur server - which, according to the Imgur error documentation, means I am missing or have incorrect parameters.

I know the parameters are correct as I have tested them directly in the browser URL (which successfully uploads an image) - so I must not be adding the parameters correctly within the code:

private void addImage(){
    String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode("http://www.lefthandedtoons.com/toons/justin_pooling.gif", "UTF-8");
    data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("myPublicConsumerKey", "UTF-8");

    // Send data
    java.net.URL url = new java.net.URL("http://api.imgur.com/2/upload.json");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        Logger.info( line );
    }
    wr.close();
    rd.close();
}

This code is based on the API examples provided by Imgur.

Can anyone tell me what I am doing wrong and how I may resolve the problem?

Thanks.


Solution

  • In this sample, imgur service returns 400 Bad Request status response with a non-empty body because of incorrect API key. In case of non successful HTTP response you shold read the response body from an error input stream. For example:

    // Get the response
    InputStream is;
    if (((HttpURLConnection) conn).getResponseCode() == 400)
        is = ((HttpURLConnection) conn).getErrorStream();
    else
        is = conn.getInputStream();
    
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    

    And, by the way your example is POST, not GET, because you are sending the parameters in the request body instead of the URL.