List of usage examples for org.apache.http.entity.mime.content FileBody FileBody
public FileBody(final File file)
From source file:com.mashape.client.http.HttpClient.java
public static <T> MashapeResponse<T> doRequest(Class<T> clazz, HttpMethod httpMethod, String url, Map<String, Object> parameters, ContentType contentType, ResponseType responseType, List<Authentication> authenticationHandlers) { if (authenticationHandlers == null) authenticationHandlers = new ArrayList<Authentication>(); if (parameters == null) parameters = new HashMap<String, Object>(); // Sanitize null parameters Set<String> keySet = new HashSet<String>(parameters.keySet()); for (String key : keySet) { if (parameters.get(key) == null) { parameters.remove(key);//from ww w . j av a2s .c o m } } List<Header> headers = new LinkedList<Header>(); // Handle authentications for (Authentication authentication : authenticationHandlers) { if (authentication instanceof HeaderAuthentication) { headers.addAll(authentication.getHeaders()); } else { Map<String, String> queryParameters = authentication.getQueryParameters(); if (authentication instanceof QueryAuthentication) { parameters.putAll(queryParameters); } else if (authentication instanceof OAuth10aAuthentication) { if (url.endsWith("/oauth_url") == false && (queryParameters == null || queryParameters.get(OAuthAuthentication.ACCESS_SECRET) == null || queryParameters.get(OAuthAuthentication.ACCESS_TOKEN) == null)) { throw new RuntimeException( "Before consuming OAuth endpoint, invoke authorize('access_token','access_secret') with not null values"); } headers.add(new BasicHeader("x-mashape-oauth-consumerkey", queryParameters.get(OAuthAuthentication.CONSUMER_KEY))); headers.add(new BasicHeader("x-mashape-oauth-consumersecret", queryParameters.get(OAuthAuthentication.CONSUMER_SECRET))); headers.add(new BasicHeader("x-mashape-oauth-accesstoken", queryParameters.get(OAuthAuthentication.ACCESS_TOKEN))); headers.add(new BasicHeader("x-mashape-oauth-accesssecret", queryParameters.get(OAuthAuthentication.ACCESS_SECRET))); } else if (authentication instanceof OAuth2Authentication) { if (url.endsWith("/oauth_url") == false && (queryParameters == null || queryParameters.get(OAuthAuthentication.ACCESS_TOKEN) == null)) { throw new RuntimeException( "Before consuming OAuth endpoint, invoke authorize('access_token') with a not null value"); } parameters.put("access_token", queryParameters.get(OAuthAuthentication.ACCESS_TOKEN)); } } } headers.add(new BasicHeader("User-Agent", USER_AGENT)); HttpUriRequest request = null; switch (httpMethod) { case GET: request = new HttpGet(url + "?" + HttpUtils.getQueryString(parameters)); break; case POST: request = new HttpPost(url); break; case PUT: request = new HttpPut(url); break; case DELETE: request = new HttpDeleteWithBody(url); break; } for (Header header : headers) { request.addHeader(header); } if (httpMethod != HttpMethod.GET) { switch (contentType) { case BINARY: MultipartEntity entity = new MultipartEntity(); for (Entry<String, Object> parameter : parameters.entrySet()) { if (parameter.getValue() instanceof File) { entity.addPart(parameter.getKey(), new FileBody((File) parameter.getValue())); } else { try { entity.addPart(parameter.getKey(), new StringBody(parameter.getValue().toString(), Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } ((HttpEntityEnclosingRequestBase) request).setEntity(entity); break; case FORM: try { ((HttpEntityEnclosingRequestBase) request) .setEntity(new UrlEncodedFormEntity(MapUtil.getList(parameters), HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } break; case JSON: throw new RuntimeException("Not supported content type: JSON"); } } org.apache.http.client.HttpClient client = new DefaultHttpClient(); try { HttpResponse response = client.execute(request); MashapeResponse<T> mashapeResponse = HttpUtils.getResponse(responseType, response); return mashapeResponse; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.box.androidlib.FileTransfer.BoxFileUpload.java
/** * Execute a file upload.//from w w w.j a v a2s.co 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 file * A File resource pointing to the file you wish to upload. Make sure File.isFile() and File.canRead() are true for this resource. * @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 File file, final String filename, final long destinationId) throws IOException, MalformedURLException, FileNotFoundException { if (!file.isFile() || !file.canRead()) { throw new FileNotFoundException("Specified upload file is either not a file, or cannot be read"); } 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.authority(BoxConfig.getInstance().getUploadUrlAuthority()); builder.path(BoxConfig.getInstance().getUploadUrlPath()); builder.appendPath(action); builder.appendPath(mAuthToken); builder.appendPath(String.valueOf(destinationId)); builder.appendQueryParameter("file_name", filename); // Set up post body final HttpPost post = new HttpPost(builder.build().toString()); final MultipartEntityWithProgressListener reqEntity = new MultipartEntityWithProgressListener( HttpMultipartMode.BROWSER_COMPATIBLE); 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(filename, new FileBody(file) { @Override public String getFilename() { return filename; } }); post.setEntity(reqEntity); // Send request final HttpResponse httpResponse; try { httpResponse = (new DefaultHttpClient()).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 (e.getMessage().equals(FileUploadListener.STATUS_CANCELLED)) { final FileResponseParser handler = new FileResponseParser(); handler.setStatus(FileUploadListener.STATUS_CANCELLED); return handler; } else { throw e; } } 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; }
From source file:org.opentraces.metatracker.net.OpenTracesClient.java
public void uploadFile(String fileName) { try {//ww w . jav a2s.c o m DefaultHttpClient httpclient = new DefaultHttpClient(); File f = new File(fileName); HttpPost httpost = new HttpPost("http://local.geotracing.com/tland/media.srv"); MultipartEntity entity = new MultipartEntity(); entity.addPart("myIdentifier", new StringBody("somevalue")); entity.addPart("myFile", new FileBody(f)); httpost.setEntity(entity); HttpResponse response; response = httpclient.execute(httpost); Log.d(LOG_TAG, "Upload result: " + response.getStatusLine()); if (entity != null) { entity.consumeContent(); } httpclient.getConnectionManager().shutdown(); } catch (Throwable ex) { Log.d(LOG_TAG, "Upload failed: " + ex.getMessage() + " Stacktrace: " + ex.getStackTrace()); } }
From source file:com.globalsight.everest.tda.TdaHelper.java
public void leverageTDA(TDATM tda, File needLeverageXliffFile, String storePath, String fileName, String sourceLocal, String targetLocal) { int timeoutConnection = 15000; HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); String loginUrl = new String(); if (tda.getHostName().indexOf("http://") < 0) { loginUrl = "http://" + tda.getHostName(); } else {/*from w w w . jav a 2 s .c o m*/ loginUrl = tda.getHostName(); } if (tda.getHostName().lastIndexOf("/") < (tda.getHostName().length() - 1)) { loginUrl = loginUrl + "/"; } try { // Judge if the TDA server has the source and target language HttpGet lanGet = new HttpGet(loginUrl + "lang/" + sourceLocal.toLowerCase() + ".json?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); HttpResponse lanRes = httpclient.execute(lanGet); StatusLine stl = lanRes.getStatusLine(); if (stl.getStatusCode() != 200) { loggerTDAInfo(stl, sourceLocal.toString()); return; } lanGet.abort(); HttpGet lanGet2 = new HttpGet(loginUrl + "lang/" + targetLocal.toLowerCase() + ".json?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); HttpResponse lanRes2 = httpclient.execute(lanGet2); stl = lanRes2.getStatusLine(); if (stl.getStatusCode() != 200) { loggerTDAInfo(stl, targetLocal.toString()); return; } lanGet2.abort(); HttpPost httpPost = new HttpPost(loginUrl + "leverage.json?action=create"); FileBody fileBody = new FileBody(needLeverageXliffFile); StringBody nameBody = new StringBody(tda.getUserName()); StringBody passwordBody = new StringBody(tda.getPassword()); StringBody appKeyBody = new StringBody(appKey); StringBody srcBody = new StringBody(sourceLocal.toLowerCase()); StringBody trBody = new StringBody(targetLocal.toLowerCase()); StringBody confirmBody = new StringBody("true"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", fileBody); reqEntity.addPart("auth_username", nameBody); reqEntity.addPart("auth_password", passwordBody); reqEntity.addPart("auth_app_key", appKeyBody); reqEntity.addPart("source_lang", srcBody); reqEntity.addPart("target_lang", trBody); reqEntity.addPart("confirm", confirmBody); httpPost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); StatusLine sl = response.getStatusLine(); if (sl.getStatusCode() != 201) { loggerTDAInfo(stl, null); return; } JSONObject jso = new JSONObject(EntityUtils.toString(entity)); JSONArray lev = jso.getJSONArray("leverage"); httpPost.abort(); if (lev.length() > 0) { JSONObject obj = lev.getJSONObject(0); String states = obj.getString("state"); // waiting the "not ready" state becoming "ready" state Thread.sleep(3 * 1000); int i = 0; if (!states.equals("ready")) { boolean flag = true; while (flag) { if (i > 40) { s_logger.info("Get TDA job status overtime. TDA job id:" + obj.getInt("id")); s_logger.info("TDA leveraging waited time:" + (40 * 3) + " seconds!"); return; } i++; HttpGet httpget = new HttpGet(loginUrl + "leverage/" + obj.getInt("id") + ".json?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); response = httpclient.execute(httpget); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { s_logger.info( "Get TDA job status error, please confirm the TDA url is correct or not! TDA job id:" + obj.getInt("id")); return; } entity = response.getEntity(); JSONObject getObj = new JSONObject(EntityUtils.toString(entity)); if (getObj.getJSONObject("leverage").getString("state").equals("ready")) { s_logger.info("TDA leveraging waited time:" + (i * 3) + " seconds!"); flag = false; } else { Thread.sleep(3 * 1000); } httpget.abort(); } } HttpPost httpPost2 = new HttpPost(loginUrl + "leverage/" + obj.getInt("id") + ".json?action=approve&auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); response = httpclient.execute(httpPost2); entity = response.getEntity(); httpPost2.abort(); HttpGet httpGet = new HttpGet(loginUrl + "leverage/" + obj.getString("id") + "/result.xlf.zip?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); HttpResponse response2 = httpclient.execute(httpGet); entity = response2.getEntity(); ZipInputStream fs = new ZipInputStream(entity.getContent()); int BUFFER = 2048; byte data[] = new byte[BUFFER]; int count; while (fs.getNextEntry() != null) { FileOutputStream fos = new FileOutputStream(storePath + File.separator + fileName); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); while ((count = fs.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } httpGet.abort(); s_logger.info("Leverage TDA TM success, TDA id:" + obj.getString("id")); } } catch (Exception e) { s_logger.error("TDA leverage process error:" + e.getMessage()); } }
From source file:cn.dacas.emmclient.security.ssl.SslHttpStack.java
/** * If Request is MultiPartRequest type, then set MultipartEntity in the httpRequest object. * @param httpRequest// ww w .j av a 2 s . c o m * @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 = ((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:com.ring.ytjojo.ssl.SslHttpStack.java
/** * If Request is MultiPartRequest type, then set MultipartEntity in the httpRequest object. * @param httpRequest/* www.ja v a2s . c o m*/ * @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:com.jelastic.JelasticService.java
public UploadResponse upload(AuthenticationResponse authenticationResponse) { UploadResponse uploadResponse = null; try {//from ww w .j a va 2 s . c o m DefaultHttpClient httpclient = getHttpClient(); final File file = new File(getDir() + File.separator + getFilename()); if (!file.exists()) { throw new IllegalArgumentException( "First build artifact and try again. Artifact not found in location: [" + file.getAbsolutePath() + "]"); } CustomMultiPartEntity multipartEntity = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, new CustomMultiPartEntity.ProgressListener() { public void transferred(long num) { if (((int) ((num / (float) totalSize) * 100)) != numSt) { System.out.println( "File Uploading : [" + (int) ((num / (float) totalSize) * 100) + "%]"); numSt = ((int) ((num / (float) totalSize) * 100)); } } }); multipartEntity.addPart("fid", new StringBody("123456")); multipartEntity.addPart("session", new StringBody(authenticationResponse.getSession())); multipartEntity.addPart("file", new FileBody(file)); totalSize = multipartEntity.getContentLength(); URI uri = URIUtils.createURI(getProtocol(), getApiHoster(), getPort(), getUrlUploader(), null, null); project.log("Upload url : " + uri.toString(), Project.MSG_DEBUG); HttpPost httpPost = new HttpPost(uri); httpPost.setEntity(multipartEntity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpPost, responseHandler); project.log("Upload response : " + responseBody, Project.MSG_DEBUG); uploadResponse = deserialize(responseBody, UploadResponse.class); } catch (URISyntaxException | IOException e) { project.log(e.getMessage(), Project.MSG_ERR); } return uploadResponse; }
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 ww w.j a v a 2 s. com HttpResponse response = client.execute(post); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { EntityUtils.consume(resEntity); } client.close(); return response; }
From source file:org.wso2.carbon.appmgt.sampledeployer.http.HttpHandler.java
public String doPostMultiData(String url, String method, MobileApplicationBean mobileApplicationBean, String cookie) throws IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Cookie", "JSESSIONID=" + cookie); MultipartEntityBuilder reqEntity;/*from w ww .j av a2 s . c o m*/ if (method.equals("upload")) { reqEntity = MultipartEntityBuilder.create(); FileBody fileBody = new FileBody(new File(mobileApplicationBean.getApkFile())); reqEntity.addPart("file", fileBody); } else { reqEntity = MultipartEntityBuilder.create(); reqEntity.addPart("version", new StringBody(mobileApplicationBean.getVersion(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("provider", new StringBody(mobileApplicationBean.getMarkettype(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("markettype", new StringBody(mobileApplicationBean.getMarkettype(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("platform", new StringBody(mobileApplicationBean.getPlatform(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("name", new StringBody(mobileApplicationBean.getName(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("description", new StringBody(mobileApplicationBean.getDescription(), ContentType.MULTIPART_FORM_DATA)); FileBody bannerImageFile = new FileBody(new File(mobileApplicationBean.getBannerFilePath())); reqEntity.addPart("bannerFile", bannerImageFile); FileBody iconImageFile = new FileBody(new File(mobileApplicationBean.getIconFile())); reqEntity.addPart("iconFile", iconImageFile); FileBody screenShot1 = new FileBody(new File(mobileApplicationBean.getScreenShot1File())); reqEntity.addPart("screenshot1File", screenShot1); FileBody screenShot2 = new FileBody(new File(mobileApplicationBean.getScreenShot2File())); reqEntity.addPart("screenshot2File", screenShot2); FileBody screenShot3 = new FileBody(new File(mobileApplicationBean.getScreenShot3File())); reqEntity.addPart("screenshot3File", screenShot3); reqEntity.addPart("addNewAssetButton", new StringBody("Submit", ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("mobileapp", new StringBody(mobileApplicationBean.getMobileapp(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("sso_ssoProvider", new StringBody(mobileApplicationBean.getSso_ssoProvider(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("appmeta", new StringBody(mobileApplicationBean.getAppmeta(), ContentType.MULTIPART_FORM_DATA)); } final HttpEntity entity = reqEntity.build(); httpPost.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpClient.execute(httpPost, responseHandler); if (!method.equals("upload")) { String id_part = responseBody.split(",")[2].split(":")[1]; return id_part.substring(2, (id_part.length() - 2)); } return responseBody; }
From source file:com.hoiio.api.FaxAPI.java
/*** * Sends a fax specified by the method parameters * @see <a href="http://developer.hoiio.com/docs/fax_send.html">http://developer.hoiio.com/docs/fax_send.html</a> * @param auth The user authorization object for the request * @param sender The sender number or caller id to be displayed * @param dest The destination to send the fax to. Phone numbers should start with a "+" and country code (E.164 format), e.g. +6511111111. * @param filepath The path of the fax to be sent * @param filename The file name of the fax desired * @return A unique reference ID for this fax transaction. This parameter will not be present if the request was not successful. * @throws HttpPostConnectionException if there is a connection failure * @throws HoiioRestException if there were problems using this REST API *///from w w w . ja va 2 s. c o m public static String sendFax(HoiioAuth auth, String sender, String dest, String filepath, String filename) throws HttpPostConnectionException, HoiioRestException { try { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost method = new HttpPost(APIUrls.SEND_FAX); MultipartEntity entity = new MultipartEntity(); entity.addPart("app_id", new StringBody(auth.getAppId(), Charset.forName("UTF-8"))); entity.addPart("access_token", new StringBody(auth.getToken(), Charset.forName("UTF-8"))); entity.addPart("dest", new StringBody(dest, Charset.forName("UTF-8"))); entity.addPart("tag", new StringBody(filename, Charset.forName("UTF-8"))); entity.addPart("filename", new StringBody(filename, Charset.forName("UTF-8"))); if (sender != null && sender.length() > 0) { entity.addPart("caller_id", new StringBody(sender, Charset.forName("UTF-8"))); } FileBody fileBody = new FileBody(new File(filepath)); entity.addPart("file", fileBody); method.setEntity(entity); log.info("executing request " + method.getRequestLine()); HttpResponse httpResponse = httpclient.execute(method); String responseBody = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8"); final APIResponse response = new APIResponse(responseBody); if (response.getStatus() == APIStatus.success_ok) { return response.getResponseMap().getString("txn_ref"); } else { log.error("Error with request: " + method.getRequestLine()); log.error(response.getResponseString()); throw new HoiioRestException(new APIRequest(APIUrls.SEND_FAX, method.getRequestLine().toString()), response); } } catch (IOException ex) { throw new HttpPostConnectionException(ex); } }