【问题标题】:URLEncode() an image file on my desktop instead of an image at a urlURLEncode() 我桌面上的图像文件而不是 url 上的图像
【发布时间】:2015-06-29 07:53:39
【问题描述】:

我目前有代码使用 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);

全班

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

返回信息:

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

【问题讨论】:

  • 为什么?您不需要 URLEncode 文件名。您也不需要对 URL 进行 URLEncode。您要解决的真正问题是什么?
  • 我正在使用(其他人的代码)将图像上传到 Imgur API。它按原样工作,但我想修改它以在我的桌面上上传图像,而不是在 url 上上传图像。您在上面看到的基本上是全部内容,但我将在整个课程中进行编辑
  • 有效的代码不会上传图片,它只是发送一个已经在互联网上的图片的 URL。
  • 您没有对图像进行 URL 编码。您正在对其 URL 进行 URLEncoding。并发送。以任何形式将本地文件名发送到另一台主机都行不通。其他主机看不到您的文件。你的问题没有意义。
  • 不清楚你在问什么。你已经完全改变了问题。它现在根本不再是关于 URLEncoding 的了。我建议你删除它并重新开始。

标签: java url encode


【解决方案1】:

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

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

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

【讨论】:

  • 感谢您的回复。哈哈,那不是我将它设置为 POST 两次(可能是哈哈)。我觉得我现在可能很接近了。我正在将数据转换为 Imgur 接受的 base64(此处说):api.imgur.com/endpoints/image 我将 convertImageData 打印到控制台,它确实是 base64。但是我收到了 404。请您快速查看我编辑的帖子,看看我是否犯了错误?
  • @Percy 完全改变问题,然后在评论中询问您已经接受的上一个问题的答案是行不通的。
  • 可能是因为 Imgur 想要 base64 而不是 encodeBase64URLSafeString
  • @Percy:400 返回码与 404 返回码完全不同。 400 表示错误请求,因此您在发送到服务器的内容中搞砸了。另外,就像 EJP 所说的那样,您最好为此提出一个全新的问题,而不是重复使用旧问题,因为这本身就是一个全新的问题。
  • @Percy 这个网站不是这样工作的。它不是一个论坛,它是一个问答网站,这不是一个“线程”,它是一个问答。这个问题应该具有永久价值。这个没有。这只是一团糟。
猜你喜欢
  • 2017-04-30
  • 2017-11-11
  • 2019-09-11
  • 1970-01-01
  • 2013-09-05
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
  • 2016-04-21
相关资源
最近更新 更多