Simple Java Imgur Upload

2019-09-21 01:39发布

问题:

I am trying to upload an image to Imgur using their API with a Java web application. I have copy-pasted this guy's code from Imgur API uploading . My method seems to run "successfully" but I don't think anything is happening. I get no feedback other than BUILD SUCCESS and am not sure how to get feedback (errors).

I am willing to spend a lot of time to get this to work but am wondering if someone can start me out by suggesting why my current implementation doesn't seem to work?

I made a plain Java class and pasted in the following:

package main;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.imageio.ImageIO;

/**
 *
 * @author J
 */
public class TestImgur1 {

     public static String getImgurContent(String clientID) throws Exception {

         clientID = "(edited out)";

    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("http://i.imgur.com/FB9OZWQ.jpg", "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();

    System.out.println(stb.toString());

    return stb.toString();
}

}

I made a 2nd plain Java class to call the 1st one so I can run it:

package main;

import java.io.IOException;


public class ImgurMainTest1 {

      public static void main(String[] args) throws IOException
  {
      try{
    TestImgur1 TestImgur1 = new TestImgur1();


  }catch (Exception e) {}
  }
}

If you could just suggest why nothing is happening (apart from BUILD SUCCESS) that would really help me get started. I have looked around for other questions/answers about the subject but it seems like everyone is trying to implement it in a different way and is really hard for me to interpret. Thankyou for reading

回答1:

just call TestImgur1.getImgurContent() in main method



标签: java api imgur