我正在使用 Restful API 开发 Google Drive API。
我需要上传文件和 json 正文。
但是当我尝试使用 java 代码上传时,我遇到了来自 google-drive 的错误代码。
==> 无效的多部分请求,包含 0 个 mime 部分
这是 Google 云端硬盘的指南。 enter image description here
这是我的代码。 我的代码有什么问题?
public int uploadFileToGoogleDrive(File file, Long acctId, String
accessToken, JSONObject json) {
HttpClient httpClient = new HttpClient();
PostMethod method = null;
Integer result = -1;
String boundary = "---------------------------" + System.currentTimeMillis();
try {
method = new PostMethod("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart");
method.setRequestHeader("Authorization", "Bearer " + accessToken);
method.setRequestHeader("Content-Type", "multipart/related; boundary=" + boundary );
Part[] parts = {new StringPart("",json.toString(),"utf-8"), new FilePart(file.getName(), file, null, "utf-8")};
//MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, method.getParams());
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
httpClient.getHttpConnectionManager().closeIdleConnections(0);
result = httpClient.executeMethod(method);
if (result == HttpStatus.SC_OK) {
InputStream rstream = null;
rstream = method.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(rstream));
String line;
while ((line = br.readLine()) != null) {
resultString += line;
}
}
System.out.println("##############################################\n" + json.toString() + "\n##############################################");
logger.debug(resultString);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
logger.error(e.getMessage(), e);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
logger.error(e.getMessage(), e);
}
catch (ProtocolException e) {
// TODO Auto-generated catch block
logger.error(e.getMessage(), e);
}
catch (IOException e) {
// TODO Auto-generated catch block
logger.error(e.getMessage(), e);
}finally {
method.releaseConnection();
}
return result;
}
}
最佳答案
multipart form uploads work just fine. Just don't specify a custom Content-Type. Your content-type is going to fail otherwise because the form-data boundary is determined by the XHR library internally. If you want to use your Content-Type, then you will have to construct your request separately and paste it as text in the "Raw" mode
关于使用 JSON 的 Java 分段文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45993424/