我尝试使用java中的其余api将文件上传到skydrive。
这是我的代码:
public void UploadFile(File upfile) {
if (upload_loc == null) {
getUploadLocation();
}
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost post = new HttpPost(upload_loc + "?" + "access_token=" + access_token);
try {
MultipartEntity mpEntity = new MultipartEntity(null,"A300x",null);
ContentBody cbFile = new FileBody(upfile, "multipart/form-data");
mpEntity.addPart("file", cbFile);
post.setEntity(mpEntity);
System.out.println(post.toString());
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line2 = "";
while ((line2 = rd.readLine()) != null) {
System.out.println(line2);
}
} catch (IOException ex) {
Logger.getLogger(Onlab.class.getName()).log(Level.SEVERE, null, ex);
}
client.getConnectionManager().shutdown();
}
但是当我尝试运行它时,我收到了这个错误:
{
"error": {
"code": "request_body_invalid",
"message": "The request entity body for multipart form-data POST isn't valid. The expected format is:\u000d\u000a--[boundary]\u000d\u000aContent-Disposition: form-data; name=\"file\"; filename=\"[FileName]\"\u000d\u000aContent-Type: application/octet-stream\u000d\u000a[CR][LF]\u000d\u000a[file contents]\u000d\u000a--[boundary]--[CR][LF]"
}
}
我最大的问题是我没有看到请求本身。我找不到任何可用的toString方法。我尝试了这种强制边界格式,但我也尝试使用空构造函数。
我的文件现在是带有一些文本的txt,我认为边界是主要问题,或者我应该配置更多参数。当我在调试模式中看到变量时,所有内容都与msdn中的指南相同。
我是其他世界的新手,如果可能的话,我想通过简单易用的HttpClient和HttpPost类保留这个apache lib。
提前致谢,对不起我的英语。
编辑: 好吧,经过长时间的睡眠后我决定尝试PUT方法而不是POST。代码可以正常工作,只需要很少的更改:
public void UploadFile(File upfile) {
if (upload_loc == null) {
getUploadLocation();
}
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
String fname=upfile.getName();
HttpPut put= new HttpPut(upload_loc +"/"+fname+ "?" + "access_token=" + access_token);
try {
FileEntity reqEntity=new FileEntity(upfile);
put.setEntity(reqEntity);
HttpResponse response = client.execute(put);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line2 = "";
while ((line2 = rd.readLine()) != null) {
System.out.println(line2);
}
} catch (IOException ex) {
Logger.getLogger(Onlab.class.getName()).log(Level.SEVERE, null, ex);
}
client.getConnectionManager().shutdown();
}
但是第一个问题还没有答案。
答案 0 :(得分:3)
两件快事:
除非确实需要,否则不应使用重载的MultipartEntity
构造函数。在这种情况下,您将charset设置为null,这可能不是一个好主意。此外,您的边界定界符不够复杂。
您的文件正文内容类型应反映正在上传的实际文件的内容。 `multipart-formdata通常用于HTML表单数据,而不是文件。您应该将其更改为“text / plain”或“image / jpeg”,或者反映文件的真实mime类型的任何内容。
一些用于调试REST请求的好工具 - REST Console (Chrome),REST Client (Firefox)。
关于您收到的错误消息的一些快速说明,它实际上有相当多的细节。该服务期望为正在发送的文件部分设置以下参数:
您可以使用以下代码设置HTTP客户端中的大部分内容:
ContentBody cbFile = new FileBody(
upfile,
"yourFileNameHere",
"application/octet-stream",
"UTF-8");