List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder setMode
public MultipartEntityBuilder setMode(final HttpMultipartMode mode)
From source file:com.microsoft.cognitive.speakerrecognition.SpeakerRestClientHelper.java
/** * Adds a stream to an HTTP entity//from ww w. j a v a2 s . com * * @param someStream Input stream to be added to an HTTP entity * @param fieldName A description of the entity content * @param fileName Name of the file attached as an entity * @return HTTP entity * @throws IOException Signals a failure while reading the input stream */ HttpEntity addStreamToEntity(InputStream someStream, String fieldName, String fileName) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int bytesRead; byte[] bytes = new byte[1024]; while ((bytesRead = someStream.read(bytes)) > 0) { byteArrayOutputStream.write(bytes, 0, bytesRead); } byte[] data = byteArrayOutputStream.toByteArray(); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.setStrictMode(); builder.addBinaryBody(fieldName, data, ContentType.MULTIPART_FORM_DATA, fileName); return builder.build(); }
From source file:objective.taskboard.it.TemplateIT.java
private HttpResponse uploadTemplate(File file) throws URISyntaxException, IOException { FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); StringBody templateName = new StringBody(file.getName(), ContentType.MULTIPART_FORM_DATA); StringBody roles = new StringBody("Role", ContentType.MULTIPART_FORM_DATA); builder.addPart("file", fileBody); builder.addPart("name", templateName); builder.addPart("roles", roles); HttpEntity entity = builder.build(); HttpPost post = new HttpPost(); post.setURI(new URI("http://localhost:8900/api/templates")); post.setHeaders(session);/*from ww w. j a va 2 s.com*/ post.setEntity(entity); return client.execute(post); }
From source file:org.lokra.seaweedfs.core.VolumeWrapper.java
/** * Upload file.// w w w . j a v a 2 s. c o m * * @param url url * @param fid fid * @param fileName fileName * @param stream stream * @param ttl ttl * @param contentType contentType * @return The size returned is the size stored on SeaweedFS. * @throws IOException Http connection is fail or server response within some error message. */ long uploadFile(String url, String fid, String fileName, InputStream stream, String ttl, ContentType contentType) throws IOException { HttpPost request; if (ttl != null) request = new HttpPost(url + "/" + fid + "?ttl=" + ttl); else request = new HttpPost(url + "/" + fid); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(CharsetUtils.get("UTF-8")); builder.addBinaryBody("upload", stream, contentType, fileName); HttpEntity entity = builder.build(); request.setEntity(entity); JsonResponse jsonResponse = connection.fetchJsonResultByRequest(request); convertResponseStatusToException(jsonResponse.statusCode, url, fid, false, false, false, false); return (Integer) objectMapper.readValue(jsonResponse.json, Map.class).get("size"); }
From source file:com.norconex.committer.gsa.GsaCommitter.java
@Override protected void commitBatch(List<ICommitOperation> batch) { File xmlFile = null;//from w ww .j ava 2s .co m try { xmlFile = File.createTempFile("batch", ".xml"); FileOutputStream fout = new FileOutputStream(xmlFile); XmlOutput xmlOutput = new XmlOutput(fout); Map<String, Integer> stats = xmlOutput.write(batch); fout.close(); HttpPost post = new HttpPost(feedUrl); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addBinaryBody("data", xmlFile, ContentType.APPLICATION_XML, xmlFile.getName()); builder.addTextBody("datasource", "GSA_Commiter"); builder.addTextBody("feedtype", "full"); HttpEntity entity = builder.build(); post.setEntity(entity); CloseableHttpResponse response = httpclient.execute(post); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { throw new CommitterException("Invalid response to Committer HTTP request. " + "Response code: " + status.getStatusCode() + ". Response Message: " + status.getReasonPhrase()); } LOG.info("Sent " + stats.get("docAdded") + " additions and " + stats.get("docRemoved") + " removals to GSA"); } catch (Exception e) { throw new CommitterException("Cannot index document batch to GSA.", e); } finally { FileUtils.deleteQuietly(xmlFile); } }
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);// ww w. j av 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:net.ychron.unirestinst.request.body.MultipartBody.java
public HttpEntity getEntity() { if (hasFile) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); if (mode != null) { builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); }// w ww. j ava 2 s.c o m for (String key : parameters.keySet()) { List<Object> value = parameters.get(key); ContentType contentType = contentTypes.get(key); for (Object cur : value) { if (cur instanceof File) { File file = (File) cur; builder.addPart(key, new FileBody(file, contentType, file.getName())); } else if (cur instanceof InputStreamBody) { builder.addPart(key, (ContentBody) cur); } else if (cur instanceof ByteArrayBody) { builder.addPart(key, (ContentBody) cur); } else { builder.addPart(key, new StringBody(cur.toString(), contentType)); } } } return builder.build(); } else { try { return new UrlEncodedFormEntity(MapUtil.getList(parameters), UTF_8); } catch (UnsupportedEncodingException e) { throw new RuntimeException(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()); }/*from ww w .jav a2 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.flowable.ui.modeler.service.AppDefinitionPublishService.java
protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey, String deploymentName) {//from www .ja v a2s . com String deployApiUrl = modelerAppProperties.getDeploymentApiUrl(); Assert.hasText(deployApiUrl, "flowable.modeler.app.deployment-api-url must be set"); String basicAuthUser = properties.getIdmAdmin().getUser(); String basicAuthPassword = properties.getIdmAdmin().getPassword(); String tenantId = tenantProvider.getTenantId(); if (!deployApiUrl.endsWith("/")) { deployApiUrl = deployApiUrl.concat("/"); } deployApiUrl = deployApiUrl .concat(String.format("app-repository/deployments?deploymentKey=%s&deploymentName=%s", encode(deploymentKey), encode(deploymentName))); if (tenantId != null) { StringBuilder sb = new StringBuilder(deployApiUrl); sb.append("&tenantId=").append(encode(tenantId)); deployApiUrl = sb.toString(); } HttpPost httpPost = new HttpPost(deployApiUrl); httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.getEncoder() .encode((basicAuthUser + ":" + basicAuthPassword).getBytes(Charset.forName("UTF-8"))))); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); entityBuilder.addBinaryBody("artifact", zipArtifact, ContentType.DEFAULT_BINARY, artifactName); HttpEntity entity = entityBuilder.build(); httpPost.setEntity(entity); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); clientBuilder .setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } })); } catch (Exception e) { LOGGER.error("Could not configure SSL for http client", e); throw new InternalServerErrorException("Could not configure SSL for http client", e); } CloseableHttpClient client = clientBuilder.build(); try { HttpResponse response = client.execute(httpPost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) { return; } else { LOGGER.error("Invalid deploy result code: {} for url", response.getStatusLine() + httpPost.getURI().toString()); throw new InternalServerErrorException("Invalid deploy result code: " + response.getStatusLine()); } } catch (IOException ioe) { LOGGER.error("Error calling deploy endpoint", ioe); throw new InternalServerErrorException("Error calling deploy endpoint: " + ioe.getMessage()); } finally { if (client != null) { try { client.close(); } catch (IOException e) { LOGGER.warn("Exception while closing http client", e); } } } }
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 w w w . j a v a 2s . c om // 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); } }