List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder create
public static MultipartEntityBuilder create()
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 {/*from w ww .ja v a2 s . 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 /*from w w w . j a v a2 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.usc.wechat.mp.sdk.util.platform.MediaUtil.java
public static MediaJsonRtn uploadMedia(License license, MediaFile mediaFile) { if (mediaFile == null) { return JsonRtnUtil.buildFailureJsonRtn(MediaJsonRtn.class, "missing mediaFile"); }/*from w w w.ja v a 2 s. c o m*/ // maybe todo more mediaFile legality check String accessToken = AccessTokenUtil.getAccessToken(license); String url = WechatRequest.UPLOAD_MEDIA.getUrl(); try { MediaType mediaType = mediaFile.getMediaType(); URI uri = new URIBuilder(url).setParameter("access_token", accessToken) .setParameter("type", mediaType.getName()).build(); HttpEntity httpEntity = MultipartEntityBuilder.create().addBinaryBody("body", mediaFile.getFile()) .build(); String rtnJson = Request.Post(uri).connectTimeout(HttpUtil.CONNECT_TIMEOUT) .socketTimeout(HttpUtil.SOCKET_TIMEOUT).body(httpEntity).execute() .handleResponse(HttpUtil.UTF8_CONTENT_HANDLER); MediaJsonRtn jsonRtn = JsonRtnUtil.parseJsonRtn(rtnJson, MediaJsonRtn.class); log.info("upload media:\n url={},\n body={},\n rtn={},{}", uri, mediaFile, rtnJson, jsonRtn); return jsonRtn; } catch (Exception e) { String msg = "upload media failed:\n " + "url=" + url + "?access_token=" + accessToken + ",\n body=" + mediaFile; log.error(msg, e); return JsonRtnUtil.buildFailureJsonRtn(MediaJsonRtn.class, "uploadMedia failed"); } }
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// w w w. ja v a 2 s . c o 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 w ww . j a v a 2 s . c o m 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// w ww .j a v a 2s . c o 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.example.SampleClient.java
private static HttpEntity createMessageForSimpleFormStreaming() { HttpEntity reqEntity = null;/*w ww .ja v a 2 s . c o m*/ try { reqEntity = MultipartEntityBuilder.create().addTextBody("name", "WSO2").addTextBody("age", "10") .addBinaryBody("file", new File( Thread.currentThread().getContextClassLoader().getResource("sample.txt").toURI()), ContentType.DEFAULT_BINARY, "sample.txt") .build(); } catch (URISyntaxException e) { log.error("Error while getting the file from resource." + e.getMessage(), e); } return reqEntity; }
From source file:org.wso2.msf4j.example.SampleClient.java
private static HttpEntity createMessageForComplexForm() { HttpEntity reqEntity = null;//from www . j a va 2s .c o m try { StringBody companyText = new StringBody("{\"type\": \"Open Source\"}", ContentType.APPLICATION_JSON); StringBody personList = new StringBody( "[{\"name\":\"Richard Stallman\",\"age\":63}, {\"name\":\"Linus Torvalds\",\"age\":46}]", ContentType.APPLICATION_JSON); reqEntity = MultipartEntityBuilder.create().addTextBody("id", "1").addPart("company", companyText) .addPart("people", personList) .addBinaryBody("file", new File( Thread.currentThread().getContextClassLoader().getResource("sample.txt").toURI()), ContentType.DEFAULT_BINARY, "sample.txt") .build(); } catch (URISyntaxException e) { log.error("Error while getting the file from resource." + e.getMessage(), e); } return reqEntity; }
From source file:org.wso2.msf4j.example.SampleClient.java
private static HttpEntity createMessageForMultipleFiles() { HttpEntity reqEntity = null;// ww w .jav a 2 s .c o m try { reqEntity = MultipartEntityBuilder.create() .addBinaryBody("files", new File(Thread.currentThread().getContextClassLoader().getResource("sample.txt") .toURI()), ContentType.DEFAULT_BINARY, "sample.txt") .addBinaryBody("files", new File( Thread.currentThread().getContextClassLoader().getResource("sample.jpg").toURI()), ContentType.DEFAULT_BINARY, "sample.jpg") .build(); } catch (URISyntaxException e) { log.error("Error while getting the file from resource." + e.getMessage(), e); } return reqEntity; }
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();//from ww w. ja v a 2 s. co m connection.setRequestProperty("Content-Type", build.getContentType().getValue()); try (OutputStream out = connection.getOutputStream()) { build.writeTo(out); } InputStream inputStream = connection.getInputStream(); String response = StreamUtil.asString(inputStream); IOUtils.closeQuietly(inputStream); connection.disconnect(); assertEquals(response, file.getName()); }