我正在尝试使用OneDrive(https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_post_content?view=odsp-graph-online)中的API上传文件。我正在使用Java和Jersey来执行此操作,但无法执行该操作。我从API得到了相同的响应(我一直在努力解决这一问题大约一个星期)。这是错误:
{
"error": {
"code": "BadRequest",
"message": "Entity only allows writes with a JSON Content-Type header.",
"innerError": {
"request-id": "3c0ea4e0-cbcc-4f11-9ca3-fc3fbfdd50bc",
"date": "2019-02-14T21:11:41"
}
}
}
让我分享我的代码:
String metadataJson
= "{"
+ "\"name\":\""+name+"\","
+ "\"file\":{},"
+ "\"@microsoft.graph.sourceUrl\":\"cid:content\","
+ "\"@microsoft.graph.conflictBehavior\":\"rename\""
+ "}";
FormDataContentDisposition fdcdMetadata = FormDataContentDisposition.name("metadata").build();
FormDataBodyPart metadataPart = new FormDataBodyPart(fdcdMetadata, metadataJson, buildChildMultipart("application", "json", "metadata"));
File tempFile = new File(this.temporaryFolderUri, tempFileName);
FormDataContentDisposition fdcdContent = FormDataContentDisposition.name("content").build();
FormDataBodyPart contentPart = new FormDataBodyPart(fdcdContent, tempFile, buildChildMultipart("plain", "text", "content"));
MultiPart nestedMultipart = new MultiPart(buildParentMultipart())
.bodyPart(metadataPart)
.bodyPart(contentPart);
return this.service.post(target, Entity.entity(nestedMultipart, nestedMultipart.getMediaType()));
。 。
public MediaType buildParentMultipart() {
final Map<String, String> parameters = new HashMap<String, String>();
parameters.put("boundary", "A100x");
MediaType mediaType = new MediaType("multipart", "form-data", parameters);
mediaType.withCharset("UTF-8");
return mediaType;
}
public MediaType buildChildMultipart(String type, String subType, String name) {
final Map<String, String> parameters = new HashMap<String, String>();
parameters.put("Content-ID", name);
MediaType mediaType = new MediaType(type, subType, parameters);
mediaType.withCharset("UTF-8");
return mediaType;
}
现在发送发送请求的代码:
public JsonObject post(WebTarget target, Entity entity) throws InterruptedException, ExecutionException {
return target.request(MediaType.APPLICATION_JSON).header(AUTHORIZATION_HEADER, getAccessToken())
.header("Content-type", MediaType.APPLICATION_JSON)
.header("accept", MediaType.APPLICATION_JSON)
.buildPost(entity)
.submit(JsonObject.class).get();
}
我在很多论坛中都在寻找任何解决方案,但是我没有运气。我在使用Node.js,C#和Javascript的项目中看到了相同的问题,但是在Java项目中(没有适用于Java的OneDrive SDK)却没有。我检查了标头,内容类型,边界,但似乎还可以。该问题似乎与元数据部分有关,但我正在设置MS要求的内容类型。你能帮我吗?谢谢你。