简体   繁体   中英

Box Java SDK: How do I configure HTTPUrlConnection for file upload?

I am developing an app that utilizes the Box Java SDK (Box Api v2). Due to our architecture, I need to upload files via the REST api. Apparently, I am having trouble getting the HTTPUrlConnection configured correctly.

Here is my code:

URL uploadURL = new URL( "https://upload.box.com/api/2.0/files/content" );
uploadConn = (HttpURLConnection)uploadURL.openConnection();
uploadConn.setRequestMethod( "POST" );
uploadConn.setChunkedStreamingMode( 0 ); // enable chunking with default chunk size
uploadConn.setRequestProperty( "Authorization", "Bearer " + boxClient.getAuthData().getAccessToken() );
uploadConn.setRequestProperty( "filename", filename );
if (isNew) uploadConn.setRequestProperty( "parent_id", parentId );

uploadConn.setDoOutput( true );`

For a new file, filename is the name of the file and parentId is the id of the target folder.

Box returns HTTP error 400, so something isn't right with my request.

Thanks in advance for your help!

the box java sdk provides methods to do file operations so you don't need to make api calls explicitly, it uses httpclient to do all the network operations. It seems you are trying to upload a file. You can do: BoxFileUploadRequestObject requestObj = BoxFileUploadRequestObject.uploadFileRequestObject(parentFolderId, "filename", file); BoxFile bFile = boxClient.getFilesManager().uploadFile(requestObj); BoxFileUploadRequestObject requestObj = BoxFileUploadRequestObject.uploadFileRequestObject(parentFolderId, "filename", file); BoxFile bFile = boxClient.getFilesManager().uploadFile(requestObj);

In case you do want to create your own http request, this upload endpoint takes in multipart entity with the following parts: 1. name: parent_id", String body: id of parent 2. name: "metadata", String body: json String of meatadata(See below) 3. file

json String of metadata: {"parent":{"id":parentid},"name":filename}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM