URLEncode() 是我桌面上的图像文件,而不是 url 中的图像

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

我目前有代码使用 URLEncoder 形成一个数据字符串,然后发送到 api。

它url 对网络上的图像进行编码。

我想对其进行更改,使其 url 改为在我的桌面上对图像进行编码。

请问我应该怎么做?是否只是我需要使用不同的语法,或者我是否需要解析桌面上的路径以便 URLEncoder 可读?

代码如下。感谢阅读

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);

整个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();
}

}

感谢好心的回答者,我已经更新了我的代码如下。但是我仍然收到 404。 base64 看起来像这样

_9j_4AAQSkZJRgABAQEASABIAAD_2wBDAAYEBQ

Imgur api 应该接受它 https://api.imgur.com/endpoints/image 我认为

代码在这里:

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();
}

return 消息:

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

只是一些避免更多可能性的快速建议:

  • HttpURLConnection 更改为 HttpsURLConnection,因为您是通过 SSL 连接但没有利用它。
  • "image" 不需要在 data 变量中进行 URL 编码。
  • 您不需要多次将方法设置为 POST :p

但对于您的问题,这是因为当您将 GET 参数发送到服务器时,服务器会在其系统而不是您的系统上对其进行解释。例如,如果 Imgur 的服务器 运行 Windows 具有有效目录和文件 C:\Users\J\Desktop\test5.jpg,服务器将使用该文件而不是您的本地文件。您的问题看起来与 this one, so try looking at the answer 非常相似。祝你好运。 :)