[英]Onedrive API file Upload using Java
我正在尝试使用POST REST调用将文件上传到OneDrive文件夹。 我的应用程序能够与OneDrive通信。 我得到的响应说The request entity body isn't a valid JSON object.
下面是我的代码,请告诉我错误的代码部分或我的方法。
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."
}
}
如果要使用POST方法,则需要POST到/api.live.net/v5.0/folder.id/files
。 您的代码缺少/files
夹ID后面的/files
部分。 如果您仍然遇到问题,显示实际HTTP请求的内容将会有所帮助。
你应该发布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客户端时,我建立了这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.