I try to upload a file to Box, using Box API.
But whatever I try, I always receive 400 Bad Request without any other information.
Any idea about the problem?
The example from the API is this curl request :
curl https://upload.box.com/api/2.0/files/content \
-H "Authorization: Bearer ACCESS_TOKEN" -X POST \
-F attributes='{"name":"tigers.jpeg", "parent":{"id":"11446498"}}' \
-F [email protected]
My code is below :
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();
}