【发布时间】:2016-05-24 13:46:39
【问题描述】:
我尝试使用 Box API 将文件上传到 Box。
但无论我尝试什么,我总是收到 400 Bad Request 没有任何其他信息。
对这个问题有任何想法吗?
API 中的示例是这个 curl 请求:
卷曲https://upload.box.com/api/2.0/files/content \
-H "授权:承载 ACCESS_TOKEN" -X POST \
-F 属性='{"name":"tigers.jpeg", "parent":{"id":"11446498"}}' \
-F 文件=@myfile.jpg
我的代码如下:
String URL = "https://upload.box.com/api/2.0/files/content/";
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(URL);
postMethod.setRequestHeader("Authorization", "Bearer "+ this.token);
try {
List<Part> parts = new ArrayList<Part>();
JSONObject parent = new JSONObject();
parent.put("id", this.parentId);
JSONObject attributes = new JSONObject();
attributes.put("parent", parent);
attributes.put("name", file.getName());
StringPart strPart = new StringPart("attributes", attributes.toString());
strPart.setContentType("application/json");
parts.add(strPart);
ByteArrayPartSource source = new ByteArrayPartSource(file.getName(),
IOUtils.toByteArray(this.file);
parts.add(new FilePart("file", source));
postMethod.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), postMethod.getParams()));
httpClient.executeMethod(postMethod);
int status = postMethod.getStatusCode();
if (status == HttpURLConnection.HTTP_OK || status == HttpURLConnection.HTTP_ACCEPTED) {
String jsonText = postMethod.getResponseBodyAsString();
JSONObject json = new JSONObject(jsonText);
System.out.println(jsonText);
} else {
throw new MyException(postMethod.getResponseBodyAsString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
postMethod.releaseConnection();
}
【问题讨论】:
标签: java rest multipartform-data box-api