java - 技术人员快进来帮帮忙啊,七牛直传报400!

 mobiledu2502860217 发布于 2022-10-31 05:46

七牛直传,报400,下面是我的方法:

 private static final String LINE_END = "\r\n";

public String postFileWithParameters(String urlStr, Map fileMap,
                                         Map paraMap) throws Exception {
        // creates a unique boundary based on time stamp
        String boundary = "<" + System.currentTimeMillis() + ">";

        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setConnectTimeout(TIMEOUT_MILLIS);
        connection.setReadTimeout(TIMEOUT_MILLIS);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + boundary);
        OutputStream outputStream = connection.getOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, CHARSET),
                true);

        if (fileMap != null) {
            Iterator> iter = fileMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = iter.next();
                String inputName = entry.getKey();
                String inputValue = entry.getValue();
                if (inputValue == null) {
                    continue;
                }
                File file = new File(inputValue);
                String fileName = file.getName();

                writer.append("--" + boundary).append(LINE_END);
                writer.append(
                        "Content-Disposition: form-data; name=\"" + inputName
    • "\"; filename=\"" + fileName + "\"")

                            .append(LINE_END);
                    writer.append(
                            "Content-Type: application/octet-stream")
                            .append(LINE_END);
                    writer.append("Content-Transfer-Encoding: binary").append(LINE_END);
                    writer.flush();
      
                    FileInputStream inputStream = new FileInputStream(file);
                    byte[] buffer = new byte[4096];
    1. bytesRead = -1;

    2. ((bytesRead = inputStream.read(buffer)) != -1) {

                        outputStream.write(buffer, 0, bytesRead);
                    }
                    outputStream.flush();
                    inputStream.close();
      
                    writer.append(LINE_END);
                    writer.flush();
      
                }
            }
    1. (paraMap != null) {

                 Iterator> iter = paraMap.entrySet().iterator();
                 while (iter.hasNext()) {
                     Map.Entry entry = iter.next();
                     String paraKey = entry.getKey();
                     String paraValue = entry.getValue();
                     writer.append("--" + boundary).append(LINE_END);
                     writer.append("Content-Disposition: form-data; name=\"" + paraKey + "\"")
                             .append(LINE_END);
                     writer.append("Content-Type: text/plain; charset=" + CHARSET).append(
                             LINE_END);
                     writer.append(paraValue).append(LINE_END);
                     writer.flush();
                 }
             }
      
             writer.append("--" + boundary + "--").append(LINE_END).flush();
             writer.close();
      
             LogX.d(urlStr, connection.getResponseCode() + "");
    2. (connection.getResponseCode()) {

                 case HttpURLConnection.HTTP_OK:
                 case HttpURLConnection.HTTP_CREATED:
                     StringBuilder sb = new StringBuilder();
                     BufferedReader br = new BufferedReader(
                             new InputStreamReader(connection.getInputStream(), "utf-8"));
                     String line = null;
                     while ((line = br.readLine()) != null) {
                         sb.append(line + "\n");
                     }
      
                     br.close();
                     LogX.d("返回", sb.toString());
                     connection.disconnect();
                     return sb.toString();
      
                 case HttpURLConnection.HTTP_UNAUTHORIZED:
                     connection.disconnect();
                     throw new IllegalArgumentException(connection.getResponseMessage());
      
                 case HttpURLConnection.HTTP_NOT_FOUND:
                     connection.disconnect();
                     throw new Exception(connection.getResponseMessage());
      
                 case HttpURLConnection.HTTP_BAD_REQUEST:
                     connection.disconnect();
                     throw new IllegalArgumentException(connection.getResponseMessage());
      
                 case HttpURLConnection.HTTP_FORBIDDEN:
                     connection.disconnect();
                     JsonObject jo = new JsonObject();
                     jo.addProperty(JSON_KEY_ERROR, ERROR_FORBIDDEN);
                     return jo.toString();
                 default:
                     connection.disconnect();
                     throw new Exception(connection.getResponseMessage());
             }
         }
         

      下面是我的传值:

      urlStr = "http://upload.qiniu.com";
      
      HashMap fileMap = new HashMap<>();
      fileMap.put("file", mPhotoPath);
      
      HashMap paraMap = new HashMap<>();
      paraMap.put("token", token);
      paraMap.put("key",key);
    1 个回答
    • 上传报文有问题,肯定是不推荐自己写的,java-SDK里面都有这些东西功能,一两行代码搞定:
      http://developer.qiniu.com/docs/v6/sdk/java-sdk.html

      具体400报错,肯定就是请求报文有问题,我是建议你抓个包看下,就是你实际上传只是提交一个http请求,而且你实现的功能是表单上传。然后你抓包看一下你的发送报文是不是跟表单的一致,最好可以把表单贴出来,跟文档中的对比一下:

      POST / HTTP/1.1
      Host:           upload.qiniu.com
      Content-Type:   multipart/form-data; boundary=<frontier>
      Content-Length: <multipartContentLength>
      
      --<frontier>
      Content-Disposition:       form-data; name="token"
      
      <uploadToken>
      --<frontier>
      Content-Disposition:       form-data; name="key"
      
      <key>
      --<frontier>
      Content-Disposition:       form-data; name="<xVariableName>"
      
      <xVariableValue>
      --<frontier>
      Content-Disposition:       form-data; name="crc32"
      
      <crc32>
      --<frontier>
      Content-Disposition:       form-data; name="accept"
      
      <acceptContentType>
      --<frontier>
      Content-Disposition:       form-data; name="file"; filename="<fileName>"
      Content-Type:              application/octet-stream
      Content-Transfer-Encoding: binary
      
      <fileBinaryData>
      --<frontier>--
      

      估计是漏了什么或者格式不对。

      2022-10-31 22:36 回答
    撰写答案
    今天,你开发时遇到什么问题呢?
    立即提问
    热门标签
    PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
    Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有