Error sending image to imgur, how to solve it? [duplicate]

2

I'm trying to send an image to Imgur but it's giving error, I can not remember how I 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, it has this IMAGEM_AQUI , when I put a link of an image type http://i.imgur.com/38KP393.png it works normally. But I wanted to know how do I get an image of my project or an object of type Image or BufferedImage when I try to put only the name type "imagem.png" it does not work ...

    
asked by anonymous 18.01.2015 / 20:10

1 answer

2

When I needed to implement a method to send images to Imgur (the way you are doing, without authentication) I ended up finding the same code that you are using (Example on API v2). I tried to use it in my application but I could not, I ended up creating a different method, if there is no problem for you to depend on other libraries, there is 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 you do not have to worry about manipulating the file, that is, creating a BufferedImage , writing the image (where you need to get the correct file extension), converting to Base64 etc. Creating a FileBody object all of these issues are resolved with a line of code: new FileBody(path.toFile()) .

The important part: The method will return a string containing the JSON response. You can use a library of your choice to handle this return to filter and manipulate 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");
18.01.2015 / 22:52