List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder addBinaryBody
public MultipartEntityBuilder addBinaryBody(final String name, final InputStream stream, final ContentType contentType, final String filename)
From source file:de.yaio.commons.http.HttpUtils.java
/** * execute POST-Request for url with params * @param baseUrl the url to call * @param username username for auth * @param password password for auth * @param params params for the request * @param textFileParams text-files to upload * @param binFileParams bin-files to upload * @return HttpResponse * @throws IOException possible Exception if Request-state <200 > 299 *//* ww w . java 2 s .c o m*/ public static HttpResponse callPostUrlPure(final String baseUrl, final String username, final String password, final Map<String, String> params, final Map<String, String> textFileParams, final Map<String, String> binFileParams) throws IOException { // create request HttpPost request = new HttpPost(baseUrl); // map params MultipartEntityBuilder builder = MultipartEntityBuilder.create(); if (MapUtils.isNotEmpty(params)) { for (String key : params.keySet()) { builder.addTextBody(key, params.get(key), ContentType.TEXT_PLAIN); } } // map files if (MapUtils.isNotEmpty(textFileParams)) { for (String key : textFileParams.keySet()) { File file = new File(textFileParams.get(key)); builder.addBinaryBody(key, file, ContentType.DEFAULT_TEXT, textFileParams.get(key)); } } // map files if (MapUtils.isNotEmpty(binFileParams)) { for (String key : binFileParams.keySet()) { File file = new File(binFileParams.get(key)); builder.addBinaryBody(key, file, ContentType.DEFAULT_BINARY, binFileParams.get(key)); } } // set request HttpEntity multipart = builder.build(); request.setEntity(multipart); // add request header request.addHeader("User-Agent", "YAIOCaller"); // call url if (LOGGER.isDebugEnabled()) { LOGGER.debug("Sending 'POST' request to URL : " + baseUrl); } HttpResponse response = executeRequest(request, username, password); // get response int retCode = response.getStatusLine().getStatusCode(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Response Code : " + retCode); } return response; }
From source file:de.yaio.commons.http.HttpUtils.java
/** * execute POST-Request for url with params * @param baseUrl the url to call * @param username username for auth * @param password password for auth * @param params params for the request * @param textFileParams text-files to upload * @param binFileParams bin-files to upload * @return HttpResponse * @throws IOException possible Exception if Request-state <200 > 299 */// w ww .j av a 2 s.c o m public static HttpResponse callPatchUrlPure(final String baseUrl, final String username, final String password, final Map<String, String> params, final Map<String, String> textFileParams, final Map<String, String> binFileParams) throws IOException { // create request HttpPatch request = new HttpPatch(baseUrl); // map params MultipartEntityBuilder builder = MultipartEntityBuilder.create(); if (MapUtils.isNotEmpty(params)) { for (String key : params.keySet()) { builder.addTextBody(key, params.get(key), ContentType.TEXT_PLAIN); } } // map files if (MapUtils.isNotEmpty(textFileParams)) { for (String key : textFileParams.keySet()) { File file = new File(textFileParams.get(key)); builder.addBinaryBody(key, file, ContentType.DEFAULT_TEXT, textFileParams.get(key)); } } // map files if (MapUtils.isNotEmpty(binFileParams)) { for (String key : binFileParams.keySet()) { File file = new File(binFileParams.get(key)); builder.addBinaryBody(key, file, ContentType.DEFAULT_BINARY, binFileParams.get(key)); } } // set request HttpEntity multipart = builder.build(); request.setEntity(multipart); // add request header request.addHeader("User-Agent", "YAIOCaller"); // call url if (LOGGER.isDebugEnabled()) { LOGGER.debug("Sending 'PATCH' request to URL : " + baseUrl); } HttpResponse response = executeRequest(request, username, password); // get response int retCode = response.getStatusLine().getStatusCode(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Response Code : " + retCode); } return response; }
From source file:groovyx.net.http.ApacheEncoders.java
/** * Encodes multipart/form-data where the body content must be an instance of the {@link MultipartContent} class. Individual parts will be * encoded using the encoders available to the {@link ChainedHttpConfig} object. * * @param config the chained configuration object * @param ts the server adapter//from ww w .j a v a 2 s .c o m */ public static void multipart(final ChainedHttpConfig config, final ToServer ts) { try { final ChainedHttpConfig.ChainedRequest request = config.getChainedRequest(); final Object body = request.actualBody(); if (!(body instanceof MultipartContent)) { throw new IllegalArgumentException("Multipart body content must be MultipartContent."); } final String contentType = request.actualContentType(); if (!(contentType.equals(MULTIPART_FORMDATA.getAt(0)) || contentType.equals(MULTIPART_MIXED.getAt(0)))) { throw new IllegalArgumentException("Multipart body content must be multipart/form-data."); } final String boundary = randomString(10); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().setBoundary(boundary); final String boundaryContentType = "multipart/form-data; boundary=" + boundary; entityBuilder.setContentType(ContentType.parse(boundaryContentType)); for (final MultipartContent.MultipartPart mpe : ((MultipartContent) body).parts()) { if (mpe.getFileName() == null) { entityBuilder.addTextBody(mpe.getFieldName(), (String) mpe.getContent()); } else { final byte[] encodedBytes = EmbeddedEncoder.encode(config, mpe.getContentType(), mpe.getContent()); entityBuilder.addBinaryBody(mpe.getFieldName(), encodedBytes, parse(mpe.getContentType()), mpe.getFileName()); } } request.setContentType(boundaryContentType); ts.toServer(entityBuilder.build().getContent()); } catch (IOException ioe) { ioe.printStackTrace(); } }
From source file:gda.util.ElogEntry.java
/** * Creates an ELog entry. Default ELog server is "http://rdb.pri.diamond.ac.uk/devl/php/elog/cs_logentryext_bl.php" * which is the development database. "http://rdb.pri.diamond.ac.uk/php/elog/cs_logentryext_bl.php" is the * production database. The java.properties file contains the property "gda.elog.targeturl" which can be set to be * either the development or production databases. * /*from w w w. j a va2 s. c o m*/ * @param title * The ELog title * @param content * The ELog content * @param userID * The user ID e.g. epics or gda or abc12345 * @param visit * The visit number * @param logID * The type of log book, The log book ID: Beam Lines: - BLB16, BLB23, BLI02, BLI03, BLI04, BLI06, BLI11, * BLI16, BLI18, BLI19, BLI22, BLI24, BLI15, DAG = Data Acquisition, EHC = Experimental Hall * Coordinators, OM = Optics and Meteorology, OPR = Operations, E * @param groupID * The group sending the ELog, DA = Data Acquisition, EHC = Experimental Hall Coordinators, OM = Optics * and Meteorology, OPR = Operations CS = Control Systems, GroupID Can also be a beam line, * @param fileLocations * The image file names with path to upload * @throws ELogEntryException */ public static void post(String title, String content, String userID, String visit, String logID, String groupID, String[] fileLocations) throws ELogEntryException { String targetURL = POST_UPLOAD_URL; try { String entryType = "41";// entry type is always a log (41) String titleForPost = visit == null ? title : "Visit: " + visit + " - " + title; MultipartEntityBuilder request = MultipartEntityBuilder.create().addTextBody("txtTITLE", titleForPost) .addTextBody("txtCONTENT", content).addTextBody("txtLOGBOOKID", logID) .addTextBody("txtGROUPID", groupID).addTextBody("txtENTRYTYPEID", entryType) .addTextBody("txtUSERID", userID); if (fileLocations != null) { for (int i = 1; i < fileLocations.length + 1; i++) { File targetFile = new File(fileLocations[i - 1]); request = request.addBinaryBody("userfile" + i, targetFile, ContentType.create("image/png"), targetFile.getName()); } } HttpEntity entity = request.build(); targetURL = LocalProperties.get("gda.elog.targeturl", POST_UPLOAD_URL); HttpPost httpPost = new HttpPost(targetURL); httpPost.setEntity(entity); CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(httpPost); try { String responseString = EntityUtils.toString(response.getEntity()); System.out.println(responseString); if (!responseString.contains("New Log Entry ID")) { throw new ELogEntryException("Upload failed, status=" + response.getStatusLine().getStatusCode() + " response=" + responseString + " targetURL = " + targetURL + " titleForPost = " + titleForPost + " logID = " + logID + " groupID = " + groupID + " entryType = " + entryType + " userID = " + userID); } } finally { response.close(); httpClient.close(); } } catch (ELogEntryException e) { throw e; } catch (Exception e) { throw new ELogEntryException("Error in ELogger. Database:" + targetURL, e); } }
From source file:org.safegees.safegees.util.HttpUrlConnection.java
public static String performPostFileCall(String requestURL, String userCredentials, File file) { String response = null;// ww w . java 2 s . co m MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create(); reqEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //reqEntity.addPart("avatar", new FileBody(file, ContentType.MULTIPART_FORM_DATA)); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(requestURL); httppost.addHeader(KEY_HEADER_AUTHORIZED, userCredentials); httppost.addHeader("ContentType", "image/png"); httppost.addHeader("Referer", "https://safegees.appspot.com/v1/user/image/upload/"); httppost.addHeader("Origin", "https://safegees.appspot.com"); httppost.addHeader("Upgrade-Insecure-Requests", "1"); httppost.addHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"); reqEntity.addBinaryBody("avatar", file, ContentType.create("image/png"), file.getName()); httppost.setEntity(reqEntity.build()); HttpResponse httpResponse = null; try { httpResponse = httpclient.execute(httppost); Log.e("IMAGE", httpResponse.getStatusLine().getStatusCode() + ":" + httpResponse.getStatusLine().getReasonPhrase()); //response = EntityUtils.toString(httpResponse.getEntity()); response = httpResponse.getStatusLine().getReasonPhrase(); } catch (IOException e) { e.printStackTrace(); } if (httpResponse.getStatusLine().getStatusCode() == 200) return response; return null; }
From source file:com.cognifide.qa.bb.aem.content.ContentInstaller.java
/** * This method uploads, installs and replicates the package indicated by the name * provided as the method's parameter. For each of these actions activateAemPackage constructs * and sends a POST request to AEM instance. If any of the POST requests lead to NOK response, * activateAemPackage will throw an exception. * <br>//from w w w .ja v a 2s . com * Method will look for content in the location indicated by the content.path property. * The content path defaults to "src/main/content". * * @param packageName Name of the package to be activated. * @throws IOException Thrown when AEM instance returns NOK response. */ public void activateAemPackage(String packageName) throws IOException { HttpPost upload = builder.createUploadRequest(); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.addBinaryBody("package", new File(CONTENT_PATH, packageName), ContentType.DEFAULT_BINARY, packageName); entityBuilder.addTextBody("force", "true"); upload.setEntity(entityBuilder.build()); JsonObject result = sender.sendCrxRequest(upload); String path = result.get("path").getAsString(); HttpPost install = builder.createInstallRequest(path); sender.sendCrxRequest(install); HttpPost replicate = builder.createReplicateRequest(path); sender.sendCrxRequest(replicate); }
From source file:com.movilizer.mds.webservice.models.MovilizerUploadForm.java
/** * Create an HTTP multipart form to perform a request. * * @param file with the document to be uploaded. * @param filename of the document./*from w w w . ja v a 2 s. com*/ * @param systemId of Movilizer Cloud. * @param password for the system id. * @param pool to store the document at. * @param key to find the document in the pool. * @param lang of the document. * @param suffix ending of the document (".zip" for HTML5 apps). * @param ack value that the cloud will return to you when the document is uploaded. * @return HttpEntity to be used in the request. */ public HttpEntity getForm(InputStream file, String filename, long systemId, String password, String pool, String key, String lang, String suffix, String ack) { MultipartEntityBuilder form = getForm(systemId, password, pool, key, lang, suffix, ack); form.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, filename); return form.build(); }
From source file:com.movilizer.mds.webservice.models.MovilizerUploadForm.java
/** * Create an HTTP multipart form to perform a request. * * @param file with the document to be uploaded. * @param systemId of Movilizer Cloud./*from w w w . ja v a 2 s . com*/ * @param password for the system id. * @param pool to store the document at. * @param key to find the document in the pool. * @param lang of the document. * @param suffix ending of the document (".zip" for HTML5 apps). * @param ack value that the cloud will return to you when the document is uploaded. * @return HttpEntity to be used in the request. */ public HttpEntity getForm(File file, long systemId, String password, String pool, String key, String lang, String suffix, String ack) { MultipartEntityBuilder form = getForm(systemId, password, pool, key, lang, suffix, ack); form.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, file.getName()); return form.build(); }
From source file:ApkItem.java
public void uploadFile() { try {/* w w w . j a v a 2 s. c om*/ CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://192.168.1.130:8080/imooc/"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody(file.getName(), file, ContentType.APPLICATION_OCTET_STREAM, file.getName()); HttpEntity multipart = builder.build(); CountingMultipartRequestEntity.ProgressListener pListener = new CountingMultipartRequestEntity.ProgressListener() { @Override public void progress(float percentage) { apkState.setProcess((int) percentage); firePropertyChange("uploadProcess", -1, percentage); } }; httpPost.setEntity(new CountingMultipartRequestEntity.ProgressEntityWrapper(multipart, pListener)); CloseableHttpResponse response = client.execute(httpPost); client.close(); } catch (IOException ex) { ex.printStackTrace(); } }
From source file:com.jkoolcloud.tnt4j.streams.inputs.HttpStreamTest.java
@Test public void httpFilePostTest() throws Exception { HttpClientBuilder builder = HttpClientBuilder.create(); HttpClient client = builder.build(); URI url = makeURI();/*from www. ja v a 2 s .co m*/ HttpPost post = new HttpPost(url); File file = new File(samplesDir, "/http-file/log.txt"); EntityBuilder entityBuilder = EntityBuilder.create(); entityBuilder.setFile(file); entityBuilder.setContentType(ContentType.TEXT_PLAIN); MultipartEntityBuilder builder2 = MultipartEntityBuilder.create(); builder2.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, "file.ext"); // NON-NLS HttpEntity multipart = builder2.build(); post.setEntity(multipart); final HttpResponse returned = client.execute(post); assertNotNull(returned); }