List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder addBinaryBody
public MultipartEntityBuilder addBinaryBody(final String name, final InputStream stream)
From source file:org.duracloud.common.web.RestHttpHelperTest.java
@Test public void testMultipartPost() throws Exception { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("text-part", "text"); // Note: Including a file as one piece of the multipart body // causes this test to fail intermittently. Replacing it here with string bytes. builder.addBinaryBody("binary-part", "binary-content".getBytes()); HttpEntity reqEntity = builder.build(); HttpResponse response = helper.multipartPost(getUrl(), reqEntity); verifyResponse(response);// w ww. j a va 2s . c o m }
From source file:ai.susi.server.ClientConnection.java
/** * POST request//from w ww . ja v a 2s. co m * @param urlstring * @param map * @param useAuthentication * @throws ClientProtocolException * @throws IOException */ public ClientConnection(String urlstring, Map<String, byte[]> map, boolean useAuthentication) throws ClientProtocolException, IOException { this.httpClient = HttpClients.custom().useSystemProperties() .setConnectionManager(getConnctionManager(useAuthentication)) .setDefaultRequestConfig(defaultRequestConfig).build(); this.request = new HttpPost(urlstring); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (Map.Entry<String, byte[]> entry : map.entrySet()) { entityBuilder.addBinaryBody(entry.getKey(), entry.getValue()); } ((HttpPost) this.request).setEntity(entityBuilder.build()); this.request.setHeader("User-Agent", USER_AGENT); this.init(); }
From source file:net.yacy.grid.http.ClientConnection.java
/** * POST request/* w ww . ja va2 s . c om*/ * @param urlstring * @param map * @param useAuthentication * @throws ClientProtocolException * @throws IOException */ public ClientConnection(String urlstring, Map<String, byte[]> map, boolean useAuthentication) throws ClientProtocolException, IOException { this.request = new HttpPost(urlstring); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (Map.Entry<String, byte[]> entry : map.entrySet()) { entityBuilder.addBinaryBody(entry.getKey(), entry.getValue()); } ((HttpPost) this.request).setEntity(entityBuilder.build()); this.request.setHeader("User-Agent", ClientIdentification.getAgent(ClientIdentification.yacyInternetCrawlerAgentName).userAgent); this.init(); }
From source file:org.exmaralda.webservices.G2PConnector.java
public String callG2P(File bpfInFile, HashMap<String, Object> otherParameters) throws IOException, JDOMException { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); if (otherParameters != null) { builder.addTextBody("lng", (String) otherParameters.get("lng")); }//from www . j a va 2 s . c o m // add the text file builder.addTextBody("iform", "bpf"); builder.addBinaryBody("i", bpfInFile); // construct a POST request with the multipart entity HttpPost httpPost = new HttpPost(g2pURL); httpPost.setEntity(builder.build()); HttpResponse response = httpClient.execute(httpPost); HttpEntity result = response.getEntity(); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200 && result != null) { String resultAsString = EntityUtils.toString(result); BASWebServiceResult basResult = new BASWebServiceResult(resultAsString); if (!(basResult.isSuccess())) { String errorText = "Call to G2P was not successful: " + resultAsString; throw new IOException(errorText); } String bpfOutString = basResult.getDownloadText(); EntityUtils.consume(result); httpClient.close(); return bpfOutString; } else { // something went wrong, throw an exception String reason = statusLine.getReasonPhrase(); throw new IOException(reason); } }
From source file:org.piwigo.remotesync.api.client.WSClient.java
@SuppressWarnings("unchecked") protected <T extends BasicResponse> CloseableHttpResponse getHttpResponse(AbstractRequest<T> request) throws ClientException { try {/* w w w.j av a 2s. c o m*/ HttpPost method = new HttpPost(clientConfiguration.getUrl() + "/ws.php"); method.setConfig(requestConfig); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addTextBody("method", request.getWSMethodName()); for (Entry<String, Object> entry : request.getParameters().entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (value instanceof File) multipartEntityBuilder.addBinaryBody(key, (File) value); else if (value == null) multipartEntityBuilder.addTextBody(key, ""); else if (value instanceof List) { for (Object object : (List<? extends Object>) value) if (object != null) multipartEntityBuilder.addTextBody(key + "[]", object.toString()); } else if (value instanceof Enum) multipartEntityBuilder.addTextBody(key, value.toString().toLowerCase()); else multipartEntityBuilder.addTextBody(key, value.toString()); } method.setEntity(multipartEntityBuilder.build()); return getHttpClient().execute(method); } catch (SSLException e) { throw new ClientSSLException("SSL certificate exception (Please try option 'Trust SSL certificates')", e); } catch (Exception e) { throw new ClientException("Unable to send request", e); } }
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()); }// w w w . j av a 2 s .com 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:org.exmaralda.webservices.BASChunkerConnector.java
public String callChunker(File bpfInFile, File audioFile, HashMap<String, Object> otherParameters) throws IOException, JDOMException { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); System.out.println("Chunker called at " + dateFormat.format(date)); //2016/11/16 12:08:43 System.out.println("Chunker called at " + Date.); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); if (otherParameters != null) { builder.addTextBody("language", (String) otherParameters.get("language")); }/*from w w w. j av a2 s . co m*/ builder.addTextBody("aligner", "fast"); builder.addTextBody("force", "rescue"); builder.addTextBody("minanchorlength", "2"); builder.addTextBody("boost_minanchorlength", "3"); // add the text file builder.addBinaryBody("bpf", bpfInFile); // add the audio file builder.addBinaryBody("audio", audioFile); System.out.println("All parameters set. "); // construct a POST request with the multipart entity HttpPost httpPost = new HttpPost(chunkerURL); httpPost.setEntity(builder.build()); System.out.println("URI: " + httpPost.getURI().toString()); HttpResponse response = httpClient.execute(httpPost); HttpEntity result = response.getEntity(); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200 && result != null) { String resultAsString = EntityUtils.toString(result); /* <WebServiceResponseLink> <success>true</success> <downloadLink>https://clarin.phonetik.uni-muenchen.de:443/BASWebServices/data/2019.01.03_15.58.41_9D4EECAD0791F9E9ED16DF35E66D1485/IDS_ISW_Chunker_Test_16kHz_OHNE_ANFANG.par</downloadLink> <output/> <warnings/> </WebServiceResponseLink> */ // read the XML result string Document doc = FileIO.readDocumentFromString(resultAsString); // check if success == true Element successElement = (Element) XPath.selectSingleNode(doc, "//success"); if (!((successElement != null) && successElement.getText().equals("true"))) { String errorText = "Call to BASChunker was not successful: " + IOUtilities.elementToString(doc.getRootElement(), true); throw new IOException(errorText); } Element downloadLinkElement = (Element) XPath.selectSingleNode(doc, "//downloadLink"); String downloadLink = downloadLinkElement.getText(); // now we have the download link - just need to get the content as text String bpfOutString = downloadText(downloadLink); EntityUtils.consume(result); httpClient.close(); return bpfOutString; //return resultAsString; } else { // something went wrong, throw an exception String reason = statusLine.getReasonPhrase(); throw new IOException(reason); } }
From source file:net.sourceforge.jwbf.core.actions.HttpActionClient.java
@VisibleForTesting void applyToEntityBuilder(String key, Object value, Charset charset, MultipartEntityBuilder entityBuilder) { if (value != null) { if (value instanceof String) { String text = (String) value; entityBuilder.addTextBody(key, text, ContentType.create("*/*", charset)); } else if (value instanceof File) { File file = (File) value; entityBuilder.addBinaryBody(key, file); } else {/* ww w. j a v a 2s . com*/ String canonicalName = value.getClass().getCanonicalName(); throw new UnsupportedOperationException("No Handler found for " + canonicalName + ". Only String or File is accepted, " + "because http parameters knows no other types."); } } }
From source file:org.openbaton.marketplace.core.VNFPackageManagement.java
public void dispatch(VNFPackageMetadata vnfPackageMetadata) throws FailedToUploadException { RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(10000).setConnectTimeout(60000) .build();/*from w ww. ja v a 2 s .c o m*/ CloseableHttpResponse response = null; HttpPost httpPost = null; String url = "https://" + fitEagleIp + ":" + fitEaglePort + "/OpenBaton/upload/v2"; try { log.debug("Executing post on " + url); httpPost = new HttpPost(url); // httpPost.setHeader(new BasicHeader("Accept", "multipart/form-data")); // httpPost.setHeader(new BasicHeader("Content-type", "multipart/form-data")); httpPost.setHeader(new BasicHeader("username", userManagement.getCurrentUser())); httpPost.setHeader(new BasicHeader("filename", vnfPackageMetadata.getVnfPackageFileName())); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addBinaryBody("file", vnfPackageMetadata.getVnfPackageFile()); httpPost.setEntity(multipartEntityBuilder.build()); CloseableHttpClient client = getHttpClientForSsl(config); response = client.execute(httpPost); } catch (ClientProtocolException e) { httpPost.releaseConnection(); e.printStackTrace(); log.error("NotAble to upload VNFPackage"); throw new FailedToUploadException( "Not Able to upload VNFPackage to Fiteagle because: " + e.getMessage()); } catch (IOException e) { httpPost.releaseConnection(); e.printStackTrace(); httpPost.releaseConnection(); log.error("NotAble to upload VNFPackage"); throw new FailedToUploadException( "Not Able to upload VNFPackage to Fiteagle because: " + e.getMessage()); } // check response status String result = ""; if (response != null && response.getEntity() != null) { try { result = EntityUtils.toString(response.getEntity()); } catch (IOException e) { e.printStackTrace(); httpPost.releaseConnection(); throw new FailedToUploadException( "Not Able to upload VNFPackage to Fiteagle because: " + e.getMessage()); } } if (response != null && response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { log.debug("Uploaded the VNFPackage"); log.debug("received: " + result); if (vnfPackageMetadata.getRequirements() == null) { vnfPackageMetadata.setRequirements(new HashMap<String, String>()); } vnfPackageMetadata.getRequirements().put("fiteagle-id", result); } else throw new FailedToUploadException( "Not Able to upload VNFPackage to Fiteagle because: Fiteagle answered " + response.getStatusLine().getStatusCode()); httpPost.releaseConnection(); }