Error sending image to Imgur, how to resolve?

Asked

Viewed 799 times

2

I’m trying to send an image to Imgur but it’s giving error, I can’t remember how to get the image. I’m using this code:

     public static String getImgurContent() throws Exception {
        URL url;
        url = new URL("https://api.imgur.com/3/image");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(IMAGEM_AQUI, "UTF-8");

        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Authorization", "Client-ID " + "000000000");
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");

        conn.connect();
        StringBuilder stb = new StringBuilder();
        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) {
            stb.append(line).append("\n");
        }
        wr.close();
        rd.close();

        return stb.toString();
    }

Well, there’s this one IMAGEM_AQUI, when I put a link of a type image http://i.imgur.com/38KP393.png works normally. But I was wondering how do I get an image of my project or an object of the type Image or BufferedImage when I try to put just the name like "imagem.png" it doesn’t work...

1 answer

2


When I needed to implement a method for sending images to Imgur (the way you are doing, without authentication) I ended up finding the same code you are using (Example on API v2). I tried to use it in my application but could not, I ended up creating a different method, if you have no problem to depend on other libraries follows a suggestion:

public class Imgur { 
    private final String ENDPOINT  = "https://api.imgur.com/3/upload/json";
    private final String CLIENT_ID = "sua_client_id";

    public String upload(Path path){
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        entityBuilder.addPart("image", new FileBody(path.toFile()));

        HttpPost httpPost = new HttpPost(ENDPOINT);
        httpPost.setHeader("Authorization", "Client-ID "+ CLIENT_ID);
        httpPost.setEntity(entityBuilder.build());

        CloseableHttpClient closeable = HttpClients.custom()
        .setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())).build();

        String responseString = null; 
        try {

            HttpResponse response = closeable.execute(httpPost);
            responseString = EntityUtils.toString(response.getEntity());

        } catch(IOException | ParseException e){
            /* Tratamento ... */
        }
        return responseString;
    }
}

The interesting thing is that this way you don’t have to worry about manipulating the file, that is, creating a BufferedImage, write the image (where it is necessary to get the correct file extension), convert to Base64, etc. Creating an object FileBody all these issues are resolved with a line of code: new FileBody(path.toFile()).

The important part: the method will return a string containing the response JSON. You can use a library of your choice to handle this return to filter and manipulate the content.

// Faz o envio do arquivo e retorna a String contendo o JSON de resposta.
String response = upload(Paths.get("C:\\imagem.png"));  

// Obtém somente as informações sobre a foto enviada (o que realmente importa).
JSONObject responseJson = new JSONObject(response).get("data");

// Monta os links...
String imageLink = responseJson.get("link");
String deleteUrl = "http://www.imgur.com/delete/" + responseJson.get("deletehash");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.