-1

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
Percy
  • 113
  • 1
  • 2
  • 11
  • Why? You don't need to URLEncode file names. You don't need to URLEncode URLs either for that matter. What's the real problem you're trying to solve? – user207421 Apr 21 '15 at 22:34
  • I'm using (someone else's code) to upload an image to the Imgur API. It works as is but I want to modify it to upload an image on my desktop instead of one at a url. What you see above is basically the whole thing but I will edit in the entire class – Percy Apr 21 '15 at 22:38
  • 1
    The code that works, does not upload an image, it just sends a URL of an image that already is on the Internet. – Gregor Raýman Apr 21 '15 at 22:42
  • You aren't URLEncoding an image. You are URLEncoding its URL. And sending it. Sending a local filename to another host, in any form, will not work. The other host can't see your files. Your question doesn't make sense. – user207421 Apr 21 '15 at 22:47
  • I think I understand, thankyou both. I tried for literally 25 hours yesterday to host both my web application AND an image file that my application can write to that is accessible to the application (and apparently would have needed to have been accessible to the Imgur api but I just couldn't figure it out. I got my webapp onto Amazon elasticbean cloud host but then couldn't figure out where to put the image file or how to make it public without this huge process of authentication to the amazon file storage area. So I am trying to revert to desktop mode and fail again. – Percy Apr 21 '15 at 22:54
  • 1
    Unclear what you're asking. You've completely changed the question. It is now no longer about URLEncoding at all. I suggest you delete this and start again. – user207421 Apr 22 '15 at 00:25

1 Answers1

0

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. :)

Community
  • 1
  • 1
kkirigaya
  • 146
  • 10
  • 1
    thankyou for your reply. haha that was not me setting it to POST twice (probably haha). I feel like i might be close now. i am converting the data to a base64 which is accepted by Imgur (said here): https://api.imgur.com/endpoints/image I printed my convertedImageData to console and it is indeed a base64. However I am getting sent back a 404. Could you please take a quick look at my edited post and see if I made a mistake? – Percy Apr 22 '15 at 00:19
  • @Percy Completely changing the question and then asking about that in a comment to an answer to the previous question that you've already accepted isn't going to work. – user207421 Apr 22 '15 at 00:26
  • Maybe because Imgur wants base64 instead of encodeBase64URLSafeString – Percy Apr 22 '15 at 00:26
  • @Percy: A 400 return code is completely different from a 404 return code. 400 means Bad Request, so you messed up something in what you're sending to the server. Also, like what EJP said, you're better off with a whole new question for this instead of reusing your old one, since this is an entirely new problem in itself. – kkirigaya Apr 22 '15 at 00:59
  • thanks, i didn't want to make a new thread (yet) because i'm so close to the answer and the question should be trivial now. the question i am stuck on (all this time) is what is the syntax to return the MASSIVE Base64 string rather than the small one that i get from `String convertedImageData = Base64.encodeBase64URLSafeString(imageData);` i will keep googling and make a new thread if cant find. it works with dummy data i just need the syntax to make that long string instead of short one – Percy Apr 22 '15 at 01:03
  • 1
    @Percy That's not how this site works. It's not a forum, it is a question-and-answer site, and this isn't a 'thread', it is a question and answer. The question is supposed to have permanent value. This one doesn't. It's just a mess. – user207421 Apr 22 '15 at 01:12