简体   繁体   中英

Onedrive API file Upload using Java

I am trying to upload a file into OneDrive folder using POST REST call. My application is able to communicate with OneDrive. The response I am getting says The request entity body isn't a valid JSON object.

Below is my Code, Kindly let me know the wrong part of code or my approach.

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

    }

Here is the Json response I am getting from OneDrive.

{
   "error": {
      "code": "request_body_invalid", 
      "message": "The request entity body isn't a valid JSON object."
   }
}

If you want to use the POST method, you need to POST to /api.live.net/v5.0/folder.id/files . Your code is missing the /files part after the folder ID. If you still have trouble, showing a trace of what the actual HTTP request looks like would be helpful.

You should POST https://apis.live.net/v5.0/:albumId/files/:fileName[.:format] . And instead of MultipartEntity, try using ByteArrayEntity. Example:

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

That code is a snippet from OneDrive4J. Check it out at https://github.com/nicknux/onedrive4j . I built this earlier this year when I was trying to look for a OneDrive Java Client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM