我尝试使用java中的rest 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 库。
在此先感谢,对不起我的英语。
编辑:好的,经过长时间的睡眠后,我决定尝试 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();
}
但是第一个问题还没有答案。