【问题标题】:send file as a data binary to http post spring boot将文件作为数据二进制文件发送到 http post spring boot
【发布时间】:2022-08-02 16:12:57
【问题描述】:

我有一个 curl 命令:

curl -X POST \"https:example.com/upload\" -H \"accept: application/json\" -H \"Authorization: token\" -H
\"Content-Type: text/plain\" --data-binary @\"filename.txt\"

这是到目前为止的代码:

SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            URL url = new URL(\"https://example.com/upload\");
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setSSLSocketFactory(sslsocketfactory);
            conn.setRequestMethod(\"POST\");
            conn.setRequestProperty(\"accept\", \"application/json\");
            conn.setRequestProperty(\"Authorization\", encodedValue);
            conn.setRequestProperty(\"Content-Type\", \"text/plain\");
            OutputStream os = new BufferedOutputStream(conn.getOutputStream());
            byte[] bytes = Files.readAllBytes(Paths.get(filePath));
             
            os.write(bytes);
            os.flush();
            
            int respCode = conn.getResponseCode();
            System.out.println(respCode);

            if (conn.getResponseCode() != 404) {
                InputStream inputstream = conn.getInputStream();
                InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
                BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
while ((client = bufferedreader.readLine()) != null) {
                    response.getWriter().println(client);
                }
            }

我收到 404 响应。

有人可以帮我我在这里做错了什么吗?请和谢谢。

  • 如果有 404,你会怎么做?根据 API 的实现,404 可能意味着比一般的“未找到”更多?也许响应中有一些信息可以帮助您调试。
  • 不,如果我执行 curl 命令,它会正常工作,我会收到 JSON 响应。

标签: java html file http post


【解决方案1】:

你能试试吗 --header'接受:应用程序/二进制文件'卷曲?

【讨论】:

    猜你喜欢
    • 2012-02-18
    • 2016-06-07
    • 1970-01-01
    • 2011-12-01
    • 2013-02-12
    • 2012-07-09
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    相关资源
    最近更新 更多