上传图片到Imgur

时间:2014-11-18 20:56:12

标签: java imgur

我想将一张图片从我的硬盘上传到imgur并返回指向它的直接链接 图像可以添加到图像标签内的论坛帖子或其他任何内容。

我已经在imgur上注册并获得了我的应用程序的客户端ID。我在stackoverflow上尝试了各种代码示例,但都没有。请帮助我获取工作代码。请参阅下面我试过的那些。

// Stuck after "Connecting..."
public static void upload(BufferedImage image)
{
    String IMGUR_POST_URI = "https://api.imgur.com/3/upload";
    String IMGUR_API_KEY = CLIENT_ID;

    try
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        System.out.println("Writing image...");
        ImageIO.write(image, "png", baos);
        URL url = new URL(IMGUR_POST_URI);

        System.out.println("Encoding...");
        String data = URLEncoder.encode("image", "UTF-8")
                + "="
                + URLEncoder.encode(
                        Base64.encodeBase64String(baos.toByteArray())
                                .toString(), "UTF-8");
        data += "&" + URLEncoder.encode("key", "UTF-8") + "="
                + URLEncoder.encode(IMGUR_API_KEY, "UTF-8");

        System.out.println("Connecting...");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Authorization", "Client-ID "
                + IMGUR_API_KEY);
        conn.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");

        OutputStreamWriter wr = new OutputStreamWriter(
                conn.getOutputStream());

        System.out.println("Sending data...");
        wr.write(data);
        wr.flush();

        System.out.println("Finished.");

        // just display the raw response
        BufferedReader in = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null)
        {
            System.out.println(line);
        }
        in.close();

    } catch (Exception e)
    {
        System.out.println("Error: " + e.getMessage());
        e.printStackTrace();
    }
}

另一个例子:

    // Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: https://api.imgur.com/3/image
    public static String getImgurContent(String imageDir, String clientID)
        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(imageDir, "UTF-8");

    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Client-ID " + clientID);
    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();
}

最后:

// null : null
public static String Imgur(String imageDir, String clientID)
{
    // create needed strings
    String address = "https://api.imgur.com/3/image";

    // Create HTTPClient and post
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(address);

    // create base64 image
    BufferedImage image = null;
    File file = new File(imageDir);

    try
    {
        // read image
        image = ImageIO.read(file);
        ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
        ImageIO.write(image, "png", byteArray);
        byte[] byteImage = byteArray.toByteArray();
        String dataImage = new Base64().encodeAsString(byteImage);

        // add header
        post.addHeader("Authorization", "Client-ID " + clientID);
        // add image
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("image", dataImage));
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // execute
        HttpResponse response = client.execute(post);

        // read response
        BufferedReader rd = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent()));
        String all = null;

        // loop through response
        while (rd.readLine() != null)
        {
            all = all + " : " + rd.readLine();
        }

        return all;

    } catch (Exception e)
    {
        return "error: " + e.toString();
    }
}

0 个答案:

没有答案