使用Java上传OneDrive API文件

3

我正在尝试使用POST REST调用将文件上传到OneDrive文件夹。我的应用程序能够与OneDrive通信。但是,我得到的响应说请求实体主体不是有效的JSON对象。

以下是我的代码,请让我知道代码的错误部分或我的方法。

public static void onedriveFileUpload() {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost uploadFile = new HttpPost("https://apis.live.net/v5.0/folder.id");

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        uploadFile.addHeader("Authorization", "Bearer access_token");
        builder.addPart("file", new FileBody(new File("Test.txt"), ContentType.APPLICATION_OCTET_STREAM, "Test.txt"));

        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        Charset chars = Charset.forName("utf-8");
        builder.setCharset(chars);
        uploadFile.setEntity(builder.build());
        uploadFile.setHeader("Content-Type", "multipart/form-data");
        uploadFile.setHeader("charset", "UTF-8");
        uploadFile.setHeader("boundary", "AaB03x");
        HttpResponse response = null;
    try {
        response = httpClient.execute(uploadFile);
        HttpEntity responseEntity = response.getEntity();
        String json = EntityUtils.toString(responseEntity);
        System.out.println(json);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    }

这是我从OneDrive获取的Json响应。
{
   "error": {
      "code": "request_body_invalid", 
      "message": "The request entity body isn't a valid JSON object."
   }
}

这种错误最好使用 Fiddler 进行调试,http://www.telerik.com/fiddler。如果不知道请求的内容,那么只能猜测发送的请求出了什么问题。 - Peter Nied
2个回答

1
你应该使用POST方法提交https://apis.live.net/v5.0/:albumId/files/:fileName[.:format]。而且不要使用MultipartEntity,尝试使用ByteArrayEntity。例如:
public Photo uploadPhoto(String accessToken, String albumId, String format, byte[] bytes) throws IOException {
    Photo newPhoto = null;
    URI uri;
    try {
        uri = new URIBuilder().setScheme(DEFAULT_SCHEME)
                              .setHost(API_HOST)
                              .setPath("/" + albumId + "/files/" + 
                                       UUID.randomUUID().toString() + "." + format)
                              .addParameter("access_token", accessToken)
                              .addParameter("downsize_photo_uploads", "false")
                              .build();
    } catch (URISyntaxException e) {
        e.printStackTrace();
        throw new IllegalStateException("Invalid album path");
    }

    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPut httpPut = new HttpPut(uri);
        ByteArrayEntity imageEntity = new ByteArrayEntity(bytes);
        httpPut.setEntity(imageEntity);
        Map<Object, Object> rawResponse = httpClient.execute(httpPut, new SomeCustomResponseHandler());
        if (rawResponse != null) {
            newPhoto = new Photo();
            newPhoto.setName((String) rawResponse.get("name"));
            newPhoto.setId((String) rawResponse.get("id"));
            // TODO:: Do something else.
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        httpClient.close();
    }

    return newPhoto;
}

这段代码是从OneDrive4J中提取的。你可以在https://github.com/nicknux/onedrive4j上查看它。我在今年早些时候构建了它,当时我正在寻找一个OneDrive Java客户端。


0
如果你想使用POST方法,你需要将数据POST到/api.live.net/v5.0/folder.id/files。你的代码在文件夹ID后面缺少了/files部分。如果仍然遇到问题,展示一下实际的HTTP请求的追踪信息会很有帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接