使用JSON上传Java多部分文件



我正在使用Restful API开发Google Drive API。

我需要上传一个文件和json主体。

但当我尝试用我的java代码上传时,我遇到了来自谷歌驱动器的错误代码。

===>包含0个mime部分的无效多部分请求

这是谷歌硬盘的指南。在此处输入图像描述

这是我的密码。我的代码出了什么问题?

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

}

多部分表单上传工作正常。只是不要指定自定义内容类型。否则,您的内容类型将失败,因为表单数据边界由XHR库内部确定。如果你如果要使用您的内容类型,则必须构造单独请求并将其粘贴为"原始"模式中的文本

查看中的此讨论还有这个

最新更新