List of usage examples for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE
HttpMultipartMode BROWSER_COMPATIBLE
To view the source code for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE.
Click Source Link
From source file:com.ring.ytjojo.ssl.SslHttpStack.java
/** * If Request is MultiPartRequest type, then set MultipartEntity in the httpRequest object. * @param httpRequest/*from w w w . j a va 2s.com*/ * @param request * @throws AuthFailureError */ private static void setMultiPartBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request) throws AuthFailureError { // Return if Request is not MultiPartRequest if (request instanceof MultiPartRequest == false) { return; } MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); //Iterate the fileUploads Map<String, File> fileUpload = ((com.ring.ytjojo.volley.MultiPartRequest) request).getFileUploads(); for (Map.Entry<String, File> entry : fileUpload.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); multipartEntity.addPart(((String) entry.getKey()), new FileBody((File) entry.getValue())); } //Iterate the stringUploads Map<String, String> stringUpload = ((MultiPartRequest) request).getStringUploads(); for (Map.Entry<String, String> entry : stringUpload.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); try { multipartEntity.addPart(((String) entry.getKey()), new StringBody((String) entry.getValue())); } catch (Exception e) { e.printStackTrace(); } } httpRequest.setEntity(multipartEntity); }
From source file:jog.my.memory.gcm.ServerUtilities.java
/** * Uploads a file to the server.//from w w w .j av a 2 s .c o m * @param context - Context of the app where the file is * @param serverUrl - URL of the server * @param uri - URI of the file * @return - response of posting the file to server */ public static String postFile(Context context, String serverUrl, Uri uri) { //TODO: Get the location sent up in here too! HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(serverUrl + "/upload"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // //Create the FileBody // final File file = new File(uri.getPath()); // FileBody fb = new FileBody(file); // deal with the file ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Bitmap bitmap = BitmapFactory.decodeFile(getRealPathFromURI(uri, context)); bitmap.compress(Bitmap.CompressFormat.JPEG, 75, byteArrayOutputStream); byte[] byteData = byteArrayOutputStream.toByteArray(); //String strData = Base64.encodeToString(data, Base64.DEFAULT); // I have no idea why Im doing this ByteArrayBody byteArrayBody = new ByteArrayBody(byteData, "image"); // second parameter is the name of the image (//TODO HOW DO I MAKE IT USE THE IMAGE FILENAME?) builder.addPart("myFile", byteArrayBody); builder.addTextBody("foo", "test text"); HttpEntity entity = builder.build(); post.setEntity(entity); try { HttpResponse response = client.execute(post); Log.d(TAG, "The response code was: " + response.getStatusLine().getStatusCode()); } catch (Exception e) { Log.d(TAG, "The image was not successfully uploaded."); } return null; // HttpClient httpclient = new DefaultHttpClient(); // HttpPost httppost = new HttpPost(serverUrl+"/postFile.do"); // // InputStream stream = null; // try { // stream = context.getContentResolver().openInputStream(uri); // // InputStreamEntity reqEntity = new InputStreamEntity(stream, -1); // // httppost.setEntity(reqEntity); // // HttpResponse response = httpclient.execute(httppost); // Log.d(TAG,"The response code was: "+response.getStatusLine().getStatusCode()); // if (response.getStatusLine().getStatusCode() == 200) { // // file uploaded successfully! // } else { // throw new RuntimeException("server couldn't handle request"); // } // return response.toString(); // } catch (Exception e) { // e.printStackTrace(); // // // handle error // } finally { // try { // stream.close(); // }catch(IOException ioe){ // ioe.printStackTrace(); // } // } // return null; }
From source file:MainFrame.HttpCommunicator.java
public boolean removeLessons(JSONObject jsObj) throws MalformedURLException, IOException { String response = null;/* w w w .ja v a 2 s .c o m*/ if (SingleDataHolder.getInstance().isProxyActivated) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword)); HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider) .build(); HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress, SingleDataHolder.getInstance().proxyPort); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php"); post.setConfig(config); StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("apideskviewer.getAllLessons", head); HttpEntity entity = builder.build(); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(post, responseHandler); System.out.println("responseBody : " + response); } else { HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php"); StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("apiDeskViewer.removeLesson", head); HttpEntity entity = builder.build(); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(post, responseHandler); System.out.println("responseBody : " + response); } if (response.equals(new String("\"success\""))) return true; else return false; }
From source file:com.codedx.burp.ExportActionListener.java
private HttpResponse sendData(File data, String urlStr) throws IOException { CloseableHttpClient client = burpExtender.getHttpClient(); if (client == null) return null; HttpPost post = new HttpPost(urlStr); post.setHeader("API-Key", burpExtender.getApiKey()); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("file", new FileBody(data)); HttpEntity entity = builder.build(); post.setEntity(entity);//from w w w . ja v a 2 s . co m HttpResponse response = client.execute(post); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { EntityUtils.consume(resEntity); } client.close(); return response; }
From source file:org.r10r.doctester.testbrowser.TestBrowserImpl.java
private Response makePatchPostOrPutRequest(Request httpRequest) { org.apache.http.HttpResponse apacheHttpClientResponse; Response response = null;// w w w . j ava 2 s . c o m try { httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpEntityEnclosingRequestBase apacheHttpRequest; if (PATCH.equalsIgnoreCase(httpRequest.httpRequestType)) { apacheHttpRequest = new HttpPatch(httpRequest.uri); } else if (POST.equalsIgnoreCase(httpRequest.httpRequestType)) { apacheHttpRequest = new HttpPost(httpRequest.uri); } else { apacheHttpRequest = new HttpPut(httpRequest.uri); } if (httpRequest.headers != null) { // add all headers for (Entry<String, String> header : httpRequest.headers.entrySet()) { apacheHttpRequest.addHeader(header.getKey(), header.getValue()); } } /////////////////////////////////////////////////////////////////// // Either add form parameters... /////////////////////////////////////////////////////////////////// if (httpRequest.formParameters != null) { List<BasicNameValuePair> formparams = Lists.newArrayList(); for (Entry<String, String> parameter : httpRequest.formParameters.entrySet()) { formparams.add(new BasicNameValuePair(parameter.getKey(), parameter.getValue())); } // encode form parameters and add UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams); apacheHttpRequest.setEntity(entity); } /////////////////////////////////////////////////////////////////// // Or add multipart file upload /////////////////////////////////////////////////////////////////// if (httpRequest.filesToUpload != null) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (Map.Entry<String, File> entry : httpRequest.filesToUpload.entrySet()) { // For File parameters entity.addPart(entry.getKey(), new FileBody((File) entry.getValue())); } apacheHttpRequest.setEntity(entity); } /////////////////////////////////////////////////////////////////// // Or add payload and convert if Json or Xml /////////////////////////////////////////////////////////////////// if (httpRequest.payload != null) { if (httpRequest.headers.containsKey(HEADER_CONTENT_TYPE) && httpRequest.headers.containsValue(APPLICATION_JSON_WITH_CHARSET_UTF8)) { String string = new ObjectMapper().writeValueAsString(httpRequest.payload); StringEntity entity = new StringEntity(string, "utf-8"); entity.setContentType("application/json; charset=utf-8"); apacheHttpRequest.setEntity(entity); } else if (httpRequest.headers.containsKey(HEADER_CONTENT_TYPE) && httpRequest.headers.containsValue(APPLICATION_XML_WITH_CHARSET_UTF_8)) { String string = new XmlMapper().writeValueAsString(httpRequest.payload); StringEntity entity = new StringEntity(string, "utf-8"); entity.setContentType(APPLICATION_XML_WITH_CHARSET_UTF_8); apacheHttpRequest.setEntity(new StringEntity(string, "utf-8")); } else if (httpRequest.payload instanceof String) { StringEntity entity = new StringEntity((String) httpRequest.payload, "utf-8"); apacheHttpRequest.setEntity(entity); } else { StringEntity entity = new StringEntity(httpRequest.payload.toString(), "utf-8"); apacheHttpRequest.setEntity(entity); } } setHandleRedirect(apacheHttpRequest, httpRequest.followRedirects); // Here we go! apacheHttpClientResponse = httpClient.execute(apacheHttpRequest); response = convertFromApacheHttpResponseToDocTesterHttpResponse(apacheHttpClientResponse); apacheHttpRequest.releaseConnection(); } catch (IOException e) { logger.error("Fatal problem creating PATCH, POST or PUT request in TestBrowser", e); throw new RuntimeException(e); } return response; }
From source file:org.plos.crepo.dao.objects.impl.ContentRepoObjectDaoImpl.java
private HttpEntity getObjectEntity(String bucketName, RepoObjectInput repoObjectInput, InputStream stream, CreationMethod creationType, String contentType) { MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntityBuilder.addTextBody("key", repoObjectInput.getKey()); multipartEntityBuilder.addTextBody("bucketName", bucketName); multipartEntityBuilder.addTextBody("create", creationType.toString()); multipartEntityBuilder.addTextBody("contentType", contentType); multipartEntityBuilder.addBinaryBody("file", stream); if (repoObjectInput.getDownloadName() != null) { multipartEntityBuilder.addTextBody("downloadName", repoObjectInput.getDownloadName()); }//from ww w . j a va2 s .c om if (repoObjectInput.getTimestamp() != null) { multipartEntityBuilder.addTextBody("timestamp", repoObjectInput.getTimestamp().toString()); } if (repoObjectInput.getCreationDate() != null) { multipartEntityBuilder.addTextBody("creationDateTime", repoObjectInput.getCreationDate().toString()); } if (repoObjectInput.getTag() != null) { multipartEntityBuilder.addTextBody("tag", repoObjectInput.getTag()); } if (repoObjectInput.getUserMetadata() != null) { multipartEntityBuilder.addTextBody("userMetadata", repoObjectInput.getUserMetadata()); } return multipartEntityBuilder.build(); }
From source file:com.buffalokiwi.api.API.java
/** * Perform a post-based request to some endpoint * @param url The URL/*from w w w. ja va2 s.c om*/ * @param formData Key/Value pairs to send * @param files Key/File files to send * @param headers Extra headers to send * @return response * @throws APIException If something goes wrong */ @Override public IAPIResponse post(final String url, final List<NameValuePair> formData, final Map<String, PostFile> files, final Map<String, String> headers) throws APIException { final HttpPost post = (HttpPost) createRequest(HttpMethod.POST, url, headers); //..Create a multi-part form data entity final MultipartEntityBuilder b = MultipartEntityBuilder.create(); //..Set the mode b.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); setMultipartFileData(files, b); //..Check for non-file form data setMultipartFormData(formData, b); //..Attach the form data to the post request post.setEntity(b.build()); //..Execute the request return executeRequest(post); }
From source file:org.nasa.openspace.gc.geolocation.LocationActivity.java
public void executeMultipartPost() throws Exception { try {//from w w w .ja v a2s . c om HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://192.168.14.102/index.php/photos/upload"); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); Session.image.compress(Bitmap.CompressFormat.PNG, 100, byteStream); byte[] buffer = byteStream.toByteArray(); ByteArrayBody body = new ByteArrayBody(buffer, "profile_image"); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("gambar", body); entity.addPart("nama", new StringBody(Session.name)); //POST nama entity.addPart("keterangan", new StringBody(Session.caption)); //POST keterangan entity.addPart("lat", new StringBody(lat)); //POST keterangan entity.addPart("lon", new StringBody(longt)); //POST keterangan post.setEntity(entity); System.out.println("post entity length " + entity.getContentLength()); ResponseHandler handler = new BasicResponseHandler(); String response = client.execute(post, handler); } catch (Exception e) { Log.e(e.getClass().getName(), e.getMessage()); } }
From source file:org.witness.ssc.xfer.utils.PublishingUtils.java
public Thread videoUploadToVideoBin(final Activity activity, final Handler handler, final String video_absolutepath, final String title, final String description, final String emailAddress, final long sdrecord_id) { Log.d(TAG, "doPOSTtoVideoBin starting"); // Make the progress bar view visible. ((SSCXferActivity) activity).startedUploading(); final Resources res = activity.getResources(); Thread t = new Thread(new Runnable() { public void run() { // Do background task. boolean failed = false; HttpClient client = new DefaultHttpClient(); if (useProxy) { HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT_HTTP); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); }/* w ww .ja v a2 s. c o m*/ client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); URI url = null; try { url = new URI(res.getString(R.string.http_videobin_org_add)); } catch (URISyntaxException e) { // Ours is a fixed URL, so not likely to get here. e.printStackTrace(); return; } HttpPost post = new HttpPost(url); CustomMultiPartEntity entity = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, new ProgressListener() { int lastPercent = 0; @Override public void transferred(long num) { percentUploaded = (int) (((float) num) / ((float) totalLength) * 99f); //Log.d(TAG, "percent uploaded: " + percentUploaded + " - " + num + " / " + totalLength); if (lastPercent != percentUploaded) { ((SSCXferActivity) activity).showProgress("uploading...", percentUploaded); lastPercent = percentUploaded; } } }); File file = new File(video_absolutepath); entity.addPart(res.getString(R.string.video_bin_API_videofile), new FileBody(file)); try { entity.addPart(res.getString(R.string.video_bin_API_api), new StringBody("1", "text/plain", Charset.forName("UTF-8"))); // title entity.addPart(res.getString(R.string.video_bin_API_title), new StringBody(title, "text/plain", Charset.forName("UTF-8"))); // description entity.addPart(res.getString(R.string.video_bin_API_description), new StringBody(description, "text/plain", Charset.forName("UTF-8"))); } catch (IllegalCharsetNameException e) { // error e.printStackTrace(); failed = true; } catch (UnsupportedCharsetException e) { // error e.printStackTrace(); return; } catch (UnsupportedEncodingException e) { // error e.printStackTrace(); failed = true; } post.setEntity(entity); totalLength = entity.getContentLength(); // Here we go! String response = null; try { response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8"); } catch (ParseException e) { // error e.printStackTrace(); failed = true; } catch (ClientProtocolException e) { // error e.printStackTrace(); failed = true; } catch (IOException e) { // error e.printStackTrace(); failed = true; } client.getConnectionManager().shutdown(); if (failed) { // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((SSCXferActivity) activity).finishedUploading(false); ((SSCXferActivity) activity) .createNotification(res.getString(R.string.upload_to_videobin_org_failed_)); } }, 0); return; } Log.d(TAG, " video bin got back " + response); // XXX Convert to preference for auto-email on videobin post // XXX ADD EMAIL NOTIF to all other upload methods // stuck on YES here, if email is defined. if (emailAddress != null && response != null) { // EmailSender through IR controlled gmail system. SSLEmailSender sender = new SSLEmailSender( activity.getString(R.string.automatic_email_username), activity.getString(R.string.automatic_email_password)); // consider // this // public // knowledge. try { sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(), activity.getString(R.string.url_of_hosted_video_is_) + " " + response, // body.getText().toString(), activity.getString(R.string.automatic_email_from), // from.getText().toString(), emailAddress // to.getText().toString() ); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } } // Log record of this URL in POSTs table dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id, res.getString(R.string.http_videobin_org_add), response, ""); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((SSCXferActivity) activity).finishedUploading(true); ((SSCXferActivity) activity) .createNotification(res.getString(R.string.upload_to_videobin_org_succeeded_)); } }, 0); } }); t.start(); return t; }
From source file:com.box.androidlib.BoxFileUpload.java
/** * Execute a file upload./* w w w. j a v a2 s . c o m*/ * * @param action * Set to {@link com.box.androidlib.Box#UPLOAD_ACTION_UPLOAD} or {@link com.box.androidlib.Box#UPLOAD_ACTION_OVERWRITE} or * {@link com.box.androidlib.Box#UPLOAD_ACTION_NEW_COPY} * @param sourceInputStream * Input stream targeting the data for the file you wish to create/upload to Box. * @param filename * The desired filename on Box after upload (just the file name, do not include the path) * @param destinationId * If action is {@link com.box.androidlib.Box#UPLOAD_ACTION_UPLOAD}, then this is the folder id where the file will uploaded to. If action is * {@link com.box.androidlib.Box#UPLOAD_ACTION_OVERWRITE} or {@link com.box.androidlib.Box#UPLOAD_ACTION_NEW_COPY}, then this is the file_id that * is being overwritten, or copied. * @return A FileResponseParser with information about the upload. * @throws IOException * Can be thrown if there is no connection, or if some other connection problem exists. * @throws FileNotFoundException * File being uploaded either doesn't exist, is not a file, or cannot be read * @throws MalformedURLException * Make sure you have specified a valid upload action */ public FileResponseParser execute(final String action, final InputStream sourceInputStream, final String filename, final long destinationId) throws IOException, MalformedURLException, FileNotFoundException { if (!action.equals(Box.UPLOAD_ACTION_UPLOAD) && !action.equals(Box.UPLOAD_ACTION_OVERWRITE) && !action.equals(Box.UPLOAD_ACTION_NEW_COPY)) { throw new MalformedURLException("action must be upload, overwrite or new_copy"); } final Uri.Builder builder = new Uri.Builder(); builder.scheme(BoxConfig.getInstance().getUploadUrlScheme()); builder.encodedAuthority(BoxConfig.getInstance().getUploadUrlAuthority()); builder.path(BoxConfig.getInstance().getUploadUrlPath()); builder.appendPath(action); builder.appendPath(mAuthToken); builder.appendPath(String.valueOf(destinationId)); if (action.equals(Box.UPLOAD_ACTION_OVERWRITE)) { builder.appendQueryParameter("file_name", filename); } else if (action.equals(Box.UPLOAD_ACTION_NEW_COPY)) { builder.appendQueryParameter("new_file_name", filename); } List<BasicNameValuePair> customQueryParams = BoxConfig.getInstance().getCustomQueryParameters(); if (customQueryParams != null && customQueryParams.size() > 0) { for (BasicNameValuePair param : customQueryParams) { builder.appendQueryParameter(param.getName(), param.getValue()); } } if (BoxConfig.getInstance().getHttpLoggingEnabled()) { // DevUtils.logcat("Uploading : " + filename + " Action= " + action + " DestinionID + " + destinationId); DevUtils.logcat("Upload URL : " + builder.build().toString()); } // Set up post body final HttpPost post = new HttpPost(builder.build().toString()); final MultipartEntityWithProgressListener reqEntity = new MultipartEntityWithProgressListener( HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName(HTTP.UTF_8)); if (mListener != null && mHandler != null) { reqEntity.setProgressListener(new MultipartEntityWithProgressListener.ProgressListener() { @Override public void onTransferred(final long bytesTransferredCumulative) { mHandler.post(new Runnable() { @Override public void run() { mListener.onProgress(bytesTransferredCumulative); } }); } }); } reqEntity.addPart("file_name", new InputStreamBody(sourceInputStream, filename) { @Override public String getFilename() { return filename; } }); post.setEntity(reqEntity); // Send request final HttpResponse httpResponse; DefaultHttpClient httpClient = new DefaultHttpClient(); HttpProtocolParams.setUserAgent(httpClient.getParams(), BoxConfig.getInstance().getUserAgent()); post.setHeader("Accept-Language", BoxConfig.getInstance().getAcceptLanguage()); try { httpResponse = httpClient.execute(post); } catch (final IOException e) { // Detect if the download was cancelled through thread interrupt. See CountingOutputStream.write() for when this exception is thrown. if (BoxConfig.getInstance().getHttpLoggingEnabled()) { // DevUtils.logcat("IOException Uploading " + filename + " Exception Message: " + e.getMessage() + e.toString()); DevUtils.logcat(" Exception : " + e.toString()); e.printStackTrace(); DevUtils.logcat("Upload URL : " + builder.build().toString()); } if ((e.getMessage() != null && e.getMessage().equals(FileUploadListener.STATUS_CANCELLED)) || Thread.currentThread().isInterrupted()) { final FileResponseParser handler = new FileResponseParser(); handler.setStatus(FileUploadListener.STATUS_CANCELLED); return handler; } else { throw e; } } finally { if (httpClient != null && httpClient.getConnectionManager() != null) { httpClient.getConnectionManager().closeIdleConnections(500, TimeUnit.MILLISECONDS); } } if (BoxConfig.getInstance().getHttpLoggingEnabled()) { DevUtils.logcat("HTTP Response Code: " + httpResponse.getStatusLine().getStatusCode()); Header[] headers = httpResponse.getAllHeaders(); // DevUtils.logcat("User-Agent : " + HttpProtocolParams.getUserAgent(httpClient.getParams())); // for (Header header : headers) { // DevUtils.logcat("Response Header: " + header.toString()); // } } // Server returned a 503 Service Unavailable. Usually means a temporary unavailability. if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE) { final FileResponseParser handler = new FileResponseParser(); handler.setStatus(ResponseListener.STATUS_SERVICE_UNAVAILABLE); return handler; } String status = null; BoxFile boxFile = null; final InputStream is = httpResponse.getEntity().getContent(); final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); final StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } is.close(); httpResponse.getEntity().consumeContent(); final String xml = sb.toString(); try { final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new ByteArrayInputStream(xml.getBytes())); final Node statusNode = doc.getElementsByTagName("status").item(0); if (statusNode != null) { status = statusNode.getFirstChild().getNodeValue(); } final Element fileEl = (Element) doc.getElementsByTagName("file").item(0); if (fileEl != null) { try { boxFile = Box.getBoxFileClass().newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } for (int i = 0; i < fileEl.getAttributes().getLength(); i++) { boxFile.parseAttribute(fileEl.getAttributes().item(i).getNodeName(), fileEl.getAttributes().item(i).getNodeValue()); } } // errors are NOT returned as properly formatted XML yet so in this case the raw response is the error status code see // http://developers.box.net/w/page/12923951/ApiFunction_Upload-and-Download if (status == null) { status = xml; } } catch (final SAXException e) { // errors are NOT returned as properly formatted XML yet so in this case the raw response is the error status code see // http://developers.box.net/w/page/12923951/ApiFunction_Upload-and-Download status = xml; } catch (final ParserConfigurationException e) { e.printStackTrace(); } final FileResponseParser handler = new FileResponseParser(); handler.setFile(boxFile); handler.setStatus(status); return handler; }