List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder build
public HttpEntity build()
From source file:org.rapidoid.http.HttpClient.java
public Future<byte[]> request(String verb, String uri, Map<String, String> headers, Map<String, String> data, Map<String, String> files, byte[] body, String contentType, Callback<byte[]> callback, boolean fullResponse) { headers = U.safe(headers);/*from w w w.ja va 2 s . c o m*/ data = U.safe(data); files = U.safe(files); HttpRequestBase req; boolean canHaveBody = false; if ("GET".equalsIgnoreCase(verb)) { req = new HttpGet(uri); } else if ("DELETE".equalsIgnoreCase(verb)) { req = new HttpDelete(uri); } else if ("OPTIONS".equalsIgnoreCase(verb)) { req = new HttpOptions(uri); } else if ("HEAD".equalsIgnoreCase(verb)) { req = new HttpHead(uri); } else if ("TRACE".equalsIgnoreCase(verb)) { req = new HttpTrace(uri); } else if ("POST".equalsIgnoreCase(verb)) { req = new HttpPost(uri); canHaveBody = true; } else if ("PUT".equalsIgnoreCase(verb)) { req = new HttpPut(uri); canHaveBody = true; } else if ("PATCH".equalsIgnoreCase(verb)) { req = new HttpPatch(uri); canHaveBody = true; } else { throw U.illegalArg("Illegal HTTP verb: " + verb); } for (Entry<String, String> e : headers.entrySet()) { req.addHeader(e.getKey(), e.getValue()); } if (canHaveBody) { HttpEntityEnclosingRequestBase entityEnclosingReq = (HttpEntityEnclosingRequestBase) req; if (body != null) { NByteArrayEntity entity = new NByteArrayEntity(body); if (contentType != null) { entity.setContentType(contentType); } entityEnclosingReq.setEntity(entity); } else { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (Entry<String, String> entry : files.entrySet()) { String filename = entry.getValue(); File file = IO.file(filename); builder = builder.addBinaryBody(entry.getKey(), file, ContentType.DEFAULT_BINARY, filename); } for (Entry<String, String> entry : data.entrySet()) { builder = builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.DEFAULT_TEXT); } ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { builder.build().writeTo(stream); } catch (IOException e) { throw U.rte(e); } byte[] bytes = stream.toByteArray(); NByteArrayEntity entity = new NByteArrayEntity(bytes, ContentType.MULTIPART_FORM_DATA); entityEnclosingReq.setEntity(entity); } } Log.debug("Starting HTTP request", "request", req.getRequestLine()); return execute(client, req, callback, fullResponse); }
From source file:org.roda.core.common.SeleniumUtils.java
private static void sendPostRequest(String source) { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("input", source); HttpPost httpPost = new HttpPost("http://www.acessibilidade.gov.pt/accessmonitor/"); httpPost.setEntity(builder.build()); try {// w w w . j av a 2s .co m CloseableHttpResponse response = httpClient.execute(httpPost); System.err.println(response); for (Header h : response.getAllHeaders()) { if ("location".equalsIgnoreCase(h.getName())) { locations.put(h.getValue(), driver.getCurrentUrl()); } } } catch (IOException e) { System.err.println("Error sending POST request!"); } }
From source file:org.urbanstew.soundcloudapi.SoundCloudAPI.java
/** * Uploads an arbitrary body by performing a POST request on the "tracks" resource. * @throws OAuthExpectationFailedException * @throws OAuthMessageSignerException //ww w . j a va 2 s . c o m * @throws IOException * @throws ClientProtocolException * @throws OAuthCommunicationException */ public HttpResponse upload(ContentBody fileBody, List<NameValuePair> params) throws OAuthMessageSignerException, OAuthExpectationFailedException, ClientProtocolException, IOException, OAuthCommunicationException { HttpPost post = new HttpPost(urlEncode("tracks", null)); // fix contributed by Bjorn Roche post.getParams().setBooleanParameter("http.protocol.expect-continue", false); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); //MultipartEntity entity = new MultipartEntity(); for (NameValuePair pair : params) { try { builder.addPart(pair.getName(), new StringBodyNoHeaders(pair.getValue())); } catch (UnsupportedEncodingException e) { } } builder.addPart("track[asset_data]", fileBody); HttpEntity entity = builder.build(); post.setEntity(entity); return performRequest(post); }
From source file:org.wso2.bps.integration.common.clients.bpmn.ActivitiRestClient.java
/** * This Method is used to deploy BPMN packages to the BPMN Server * * @param fileName The name of the Package to be deployed * @param filePath The location of the BPMN package to be deployed * @throws java.io.IOException/*from w w w .j a va 2 s . co m*/ * @throws org.json.JSONException * @returns String array with status, deploymentID and Name */ public String[] deployBPMNPackage(String filePath, String fileName) throws Exception { String url = serviceURL + "repository/deployments"; HttpHost target = new HttpHost(hostname, port, "http"); DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getCredentialsProvider().setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(username, password)); HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("file", new File(filePath), ContentType.MULTIPART_FORM_DATA, fileName); HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); HttpResponse response = httpClient.execute(httpPost); String status = response.getStatusLine().toString(); String responseData = EntityUtils.toString(response.getEntity()); JSONObject jsonResponseObject = new JSONObject(responseData); if (status.contains(Integer.toString(HttpStatus.SC_CREATED)) || status.contains(Integer.toString(HttpStatus.SC_OK))) { String deploymentID = jsonResponseObject.getString("id"); String name = jsonResponseObject.getString("name"); return new String[] { status, deploymentID, name }; } else if (status.contains(Integer.toString(HttpStatus.SC_INTERNAL_SERVER_ERROR))) { String errorMessage = jsonResponseObject.getString("errorMessage"); throw new RestClientException(errorMessage); // return new String[]{status, errorMessage}; } else { throw new RestClientException("Failed to deploy package " + fileName); } }
From source file:org.wso2.carbon.apimgt.hybrid.gateway.usage.publisher.tasks.APIUsageFileUploadTask.java
/** * Uploads the API Usage file to Upload Service * * @param compressedFilePath File Path to the compressed file * @param fileName Name of the uploading file * @return Returns boolean true if uploading is successful *//*from ww w . j a va 2 s. c om*/ private boolean uploadCompressedFile(Path compressedFilePath, String fileName) { String response; try { String uploadServiceUrl = configManager .getProperty(MicroGatewayAPIUsageConstants.USAGE_UPLOAD_SERVICE_URL); uploadServiceUrl = (uploadServiceUrl != null && !uploadServiceUrl.isEmpty()) ? uploadServiceUrl : MicroGatewayAPIUsageConstants.DEFAULT_UPLOAD_SERVICE_URL; URL uploadServiceUrlValue = MicroGatewayCommonUtil.getURLFromStringUrlValue(uploadServiceUrl); HttpClient httpClient = APIUtil.getHttpClient(uploadServiceUrlValue.getPort(), uploadServiceUrlValue.getProtocol()); HttpPost httppost = new HttpPost(uploadServiceUrl); InputStream zipStream = new FileInputStream(compressedFilePath.toString()); MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create(); mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); mBuilder.addBinaryBody("file", zipStream, ContentType.create("application/zip"), fileName); HttpEntity entity = mBuilder.build(); httppost.setHeader(MicroGatewayAPIUsageConstants.FILE_NAME_HEADER, fileName); APIManagerConfiguration config = ServiceReferenceHolder.getInstance() .getAPIManagerConfigurationService().getAPIManagerConfiguration(); String username = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_USERNAME); char[] password = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_PASSWORD).toCharArray(); String authHeaderValue = TokenUtil.getBasicAuthHeaderValue(username, password); MicroGatewayCommonUtil.cleanPasswordCharArray(password); httppost.setHeader(MicroGatewayAPIUsageConstants.AUTHORIZATION_HEADER, authHeaderValue); httppost.setHeader(MicroGatewayAPIUsageConstants.ACCEPT_HEADER, MicroGatewayAPIUsageConstants.ACCEPT_HEADER_APPLICATION_JSON); httppost.setEntity(entity); response = HttpRequestUtil.executeHTTPMethodWithRetry(httpClient, httppost, MicroGatewayAPIUsageConstants.MAX_RETRY_COUNT); log.info("API Usage file : " + compressedFilePath.getFileName() + " uploaded successfully. " + "Server Response : " + response); return true; } catch (OnPremiseGatewayException e) { log.error("Error occurred while uploading API Usage file.", e); } catch (FileNotFoundException e) { log.error("Error occurred while reading API Usage file from the path.", e); } return false; }
From source file:org.wso2.ei.businessprocess.integration.common.clients.bpmn.ActivitiRestClient.java
/** * This Method is used to deploy BPMN packages to the BPMN Server * * @param fileName The name of the Package to be deployed * @param filePath The location of the BPMN package to be deployed * @throws java.io.IOException//from w ww .j a va 2 s . co m * @throws org.json.JSONException * @returns String array with status, deploymentID and Name */ public String[] deployBPMNPackage(String filePath, String fileName) throws RestClientException, IOException, JSONException { String url = serviceURL + "repository/deployments"; DefaultHttpClient httpClient = getHttpClient(); HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("file", new File(filePath), ContentType.MULTIPART_FORM_DATA, fileName); HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); HttpResponse response = httpClient.execute(httpPost); String status = response.getStatusLine().toString(); String responseData = EntityUtils.toString(response.getEntity()); JSONObject jsonResponseObject = new JSONObject(responseData); if (status.contains(Integer.toString(HttpStatus.SC_CREATED)) || status.contains(Integer.toString(HttpStatus.SC_OK))) { String deploymentID = jsonResponseObject.getString(ID); String name = jsonResponseObject.getString(NAME); return new String[] { status, deploymentID, name }; } else if (status.contains(Integer.toString(HttpStatus.SC_INTERNAL_SERVER_ERROR))) { String errorMessage = jsonResponseObject.getString("errorMessage"); throw new RestClientException(errorMessage); } else { throw new RestClientException("Failed to deploy package " + fileName); } }
From source file:org.wso2.msf4j.HttpServerTest.java
@Test public void testFormParamWithFile() throws IOException, URISyntaxException { HttpURLConnection connection = request("/test/v1/testFormParamWithFile", HttpMethod.POST); File file = new File(Thread.currentThread().getContextClassLoader().getResource("testJpgFile.jpg").toURI()); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); builder.addPart("form", fileBody); HttpEntity build = builder.build(); connection.setRequestProperty("Content-Type", build.getContentType().getValue()); try (OutputStream out = connection.getOutputStream()) { build.writeTo(out);/*from w w w. ja va2s . com*/ } InputStream inputStream = connection.getInputStream(); String response = StreamUtil.asString(inputStream); IOUtils.closeQuietly(inputStream); connection.disconnect(); assertEquals(response, file.getName()); }
From source file:xin.nic.sdk.registrar.util.HttpUtil.java
public static String doPost(String requestUrl, Map<String, String> paramsMap, Map<String, InputStream> files) throws Exception { RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(500) .setSocketTimeout(20000).setConnectTimeout(20000).build(); // ?//from w ww .java 2s.c om MultipartEntityBuilder mbuilder = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(Charset.forName(charset)); if (paramsMap != null) { Set<Entry<String, String>> paramsSet = paramsMap.entrySet(); for (Entry<String, String> entry : paramsSet) { mbuilder.addTextBody(entry.getKey(), entry.getValue(), ContentType.create("text/plain", charset)); } } if (files != null) { Set<Entry<String, InputStream>> filesSet = files.entrySet(); for (Entry<String, InputStream> entry : filesSet) { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream is = entry.getValue(); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) > 0) { os.write(buffer, 0, len); } os.close(); is.close(); mbuilder.addBinaryBody("attachment", os.toByteArray(), ContentType.APPLICATION_OCTET_STREAM, entry.getKey()); } } HttpPost httpPost = new HttpPost(requestUrl); httpPost.setConfig(requestConfig); HttpEntity httpEntity = mbuilder.build(); httpPost.setEntity(httpEntity); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { @Override public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= HttpStatus.SC_OK && status < HttpStatus.SC_MULTIPLE_CHOICES) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; return httpClient.execute(httpPost, responseHandler); }