我试图使用多部分请求将文件上传到OneDrive。我试了很多方法,但都不起作用。
请求的形式是:-
POST /drive/items/{folder-id}/children
Content-Type: multipart/related; boundary="A100x"
--A100x
Content-ID: <metadata>
Content-Type: application/json
{
"name": "newfile.txt",
"file": {},
"@content.sourceUrl": "cid:content",
"@name.conflictBehavior": "rename"
}
--A100x
Content-ID: <content>
Content-Type: text/plain
Contents of the file to be uploaded.
--A100x--
我试过很多方法。我为此编写的代码片段添加在下面。如有任何帮助,不胜感激。
片段:
HttpClient httpClient = HttpClientBuilder.create().build();
URIBuilder uriBuilder = new URIBuilder(URI);
HttpPost post = new HttpPost(uriBuilder.build());
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
Charset chars = Charset.forName("utf-8");
builder.setCharset(chars);
post.setEntity(builder.build());
builder.addPart("content", new FileBody(new File("/home/myfiles/test"), ContentType.APPLICATION_OCTET_STREAM, "test"));
builder.addPart("metadata", new StringBody(metaJson, ContentType.APPLICATION_JSON));
post.setHeader("Content-Type", "multipart/form-data");
post.addHeader("Authorization", "Bearer " + ACCESS_TOKEN);
try {
HttpResponse response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
responseBuilder = new StringBuilder();
while ((output = br.readLine()) != null) {
responseBuilder.append(output);
}
} else {
System.out.println("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
URI:
https://api.onedrive.com/v1.0/drive/root/myfile/儿童
后来我意识到我可以使用简单的文件上传,只要我的文件是简单的doc文件。并使用Apache REST客户端实现解决方案。
代码片段:- BufferedReader br = null;
String output;
StringBuilder responseBuilder = null;
HttpClient httpClient = HttpClientBuilder.create().build();
URIBuilder uriBuilder = new URIBuilder(<UPLOAD_URL>);
HttpPut request = new HttpPut(uriBuilder.build());
request.addHeader("Authorization", "Bearer " + oneDriveConnection.getAccessToken());
request.addHeader("Content-Type", mimeType);
HttpEntity entity = new ByteArrayEntity(bytes);
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode == 201 || responseCode == 200) {
br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
responseBuilder = new StringBuilder();
while ((output = br.readLine()) != null) {
responseBuilder.append(output);
}
} else {
logger.error("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
throw new UploadException("Upload failure, Status code : " + response.getStatusLine().getStatusCode());
}