Search code examples
javaurlencode

URLEncode() an image file on my desktop instead of an image at a url


I currently have code that uses URLEncoder to form a data string that I send to an api.

It url encodes an image on the web.

I want to change it so it url encodes an image on my desktop instead.

How should I go about doing this please? Is there simply a different syntax I need to use, or do I need to parse the path on my desktop so it is readable by URLEncoder?

The code is below. Thankyou for reading

url = new URL("https://api.imgur.com/3/image");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

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

            //what i want but doesnt work
              + URLEncoder.encode("C:\\Users\\J\\Desktop\\test5.jpg", "UTF-8");

            // what works but i dont want
              + 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);

The entire class

public class UploadController {

     public static String getImgurContent(String clientID) throws Exception {

//         clientID = "b290a88ad882073";

    URL url;

    url = new URL("https://api.imgur.com/3/image");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

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

            //what i want but doesnt work
              + URLEncoder.encode("C:\\Users\\J\\Desktop\\test5.jpg", "UTF-8");

            // what works but i dont want
              + 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();
}

}

Thanks to the kind answerer I have updated my code to the follow. I am still getting a 404 however. The base64 looks like this

_9j_4AAQSkZJRgABAQEASABIAAD_2wBDAAYEBQ

The Imgur api should accept it https://api.imgur.com/endpoints/image i think

The code is here:

public class UploadController {

     public static String getImgurContent(String clientID) throws Exception {

//         clientID = "b290a88ad882073";

    URL url;

    url = new URL("https://api.imgur.com/3/image");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    String file1 = "C:\\Users\\J\\Desktop\\test5.jpg";

//    convert to base64

    FileInputStream imageInFile = new FileInputStream(file1);
            byte imageData[] = new byte[(int) file1.length()];
            imageInFile.read(imageData);

            String convertedImageData = Base64.encodeBase64URLSafeString(imageData);

            System.out.println(convertedImageData);

//                String data = "image/png" + "base64" + "=" + convertedImageData;


//         sample data string
//            data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==

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

            //what i want but doesnt work
//              + URLEncoder.encode("C:\\Users\\J\\Desktop\\test5.jpg", "UTF-8");

            // what works but i dont want
//              + 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.setRequestProperty("Content-Type",
            "application/x-www-form-urlencoded");

    conn.connect();
    StringBuilder stb = new StringBuilder();
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(convertedImageData);
    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();
}

The return message:

Building g5 1.0-SNAPSHOT
------------------------------------------------------------------------

--- exec-maven-plugin:1.2.1:exec (default-cli) @ g5 ---
_9j_4AAQSkZJRgABAQEASABIAAD_2wBDAAYEBQ
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: https://api.imgur.com/3/image
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1839)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1440)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at main.UploadController.getImgurContent(UploadController.java:80)
    at main.ImgurMainTest1.main(ImgurMainTest1.java:16)
------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------
Total time: 2.003s
Finished at: Wed Apr 22 01:17:49 BST 2015
Final Memory: 5M/109M
------------------------------------------------------------------------
Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec (default-cli) on project g5: Command execution failed. Process exited with an error: 1 (Exit value: 1) -> [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.

For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

Solution

  • Just some quick suggestions to avoid any more potentialities:

    • Change HttpURLConnection to HttpsURLConnection, since you're connecting over SSL but not taking advantage of it.
    • "image" doesn't need to be URL encoded in the data variable.
    • You don't need to set the method to POST more than once :p

    But for your issue, it's because when you send that GET parametre to the server, the server is interpreting it on its system, not yours. For example, if Imgur's servers were running Windows with a valid directory and file C:\Users\J\Desktop\test5.jpg, the server would use that file instead of your local file. Your issue looks very similar to this one, so try looking at the answer for it. Best of luck. :)