Java 分段文件上传 JSON

Java Multipart File upload with JSON

我正在使用 Restful API 开发 Google 驱动器 API。

我需要上传文件和json正文。

但是当我尝试使用我的 java 代码上传时,我遇到了来自 google-drive 的错误代码。

==> 包含 0 个 MIME 部分的无效多部分请求

这是 Google-Drive 的指南。 enter image description here

这是我的代码。 我的代码有什么问题?

public int uploadFileToGoogleDrive(File file, Long acctId, String 
accessToken, JSONObject json) {
    HttpClient httpClient = new HttpClient();
    PostMethod method = null;
    Integer result = -1;
    String boundary = "---------------------------" + System.currentTimeMillis();
    try {
        method = new PostMethod("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart");
        method.setRequestHeader("Authorization", "Bearer " + accessToken);
        method.setRequestHeader("Content-Type", "multipart/related; boundary=" + boundary );

        Part[] parts = {new StringPart("",json.toString(),"utf-8"), new FilePart(file.getName(), file, null, "utf-8")};

        //MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, method.getParams());
        method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

        httpClient.getHttpConnectionManager().closeIdleConnections(0);
        result  = httpClient.executeMethod(method);

        if (result == HttpStatus.SC_OK) {
            InputStream rstream = null;
            rstream = method.getResponseBodyAsStream();
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(rstream));
            String line;
            while ((line = br.readLine()) != null) {
                resultString += line;
            }
        }
        System.out.println("##############################################\n" + json.toString() + "\n##############################################");
        logger.debug(resultString);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        logger.error(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        logger.error(e.getMessage(), e);
    }
    catch (ProtocolException e) {
        // TODO Auto-generated catch block
        logger.error(e.getMessage(), e);
    }
    catch (IOException e) {
        // TODO Auto-generated catch block
        logger.error(e.getMessage(), e);
    }finally {
        method.releaseConnection();
    }
    return result;
}

}

multipart form uploads work just fine. Just don't specify a custom Content-Type. Your content-type is going to fail otherwise because the form-data boundary is determined by the XHR library internally. If you want to use your Content-Type, then you will have to construct your request separately and paste it as text in the "Raw" mode

看看this discussiointhis one