List of usage examples for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE
HttpMultipartMode BROWSER_COMPATIBLE
To view the source code for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE.
Click Source Link
From source file:net.toxbank.client.resource.InvestigationClient.java
/** * Sets the published status for an investigation * @param investigation the investigation to update - only url is used * @param published true iff the investigation should be published *//*from ww w .j a v a2 s . c o m*/ public RemoteTask publishInvestigation(Investigation investigation, boolean published) throws Exception { if (investigation.getResourceURL() == null) { throw new IllegalArgumentException("investigation has not been assigned a resource url"); } MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, utf8); entity.addPart(published_param, new StringBody(String.valueOf(published))); RemoteTask task = new RemoteTask(getHttpClient(), investigation.getResourceURL(), "text/uri-list", entity, HttpPut.METHOD_NAME); return task; }
From source file:org.coronastreet.gpxconverter.StravaForm.java
public void upload() { //httpClient = new DefaultHttpClient(); httpClient = HttpClientBuilder.create().build(); localContext = new BasicHttpContext(); cookieStore = new BasicCookieStore(); localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); //httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); if (doLogin()) { //log("Ok....logged in..."); try {//from www .ja va2 s. c o m // Have to fetch the form to get the CSRF Token HttpGet get = new HttpGet(uploadFormURL); HttpResponse formResponse = httpClient.execute(get, localContext); //log("Fetched the upload form...: " + formResponse.getStatusLine()); org.jsoup.nodes.Document doc = Jsoup.parse(EntityUtils.toString(formResponse.getEntity())); String csrftoken, csrfparam; Elements metalinksParam = doc.select("meta[name=csrf-param]"); if (!metalinksParam.isEmpty()) { csrfparam = metalinksParam.first().attr("content"); } else { csrfparam = null; log("Missing csrf-param?"); } Elements metalinksToken = doc.select("meta[name=csrf-token]"); if (!metalinksToken.isEmpty()) { csrftoken = metalinksToken.first().attr("content"); } else { csrftoken = null; log("Missing csrf-token?"); } HttpPost request = new HttpPost(uploadURL); request.setHeader("X-CSRF-Token", csrftoken); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("method", new StringBody("post")); entity.addPart("new_uploader", new StringBody("1")); entity.addPart(csrfparam, new StringBody(csrftoken)); entity.addPart("files[]", new InputStreamBody(document2InputStream(outDoc), "application/octet-stream", "temp.tcx")); // Need to do this bit because without it you can't disable chunked encoding, and Strava doesn't support chunked. ByteArrayOutputStream bArrOS = new ByteArrayOutputStream(); entity.writeTo(bArrOS); bArrOS.flush(); ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray()); bArrOS.close(); bArrEntity.setChunked(false); bArrEntity.setContentEncoding(entity.getContentEncoding()); bArrEntity.setContentType(entity.getContentType()); request.setEntity(bArrEntity); HttpResponse response = httpClient.execute(request, localContext); if (response.getStatusLine().getStatusCode() != 200) { log("Failed to Upload"); HttpEntity en = response.getEntity(); if (en != null) { String output = EntityUtils.toString(en); log(output); } } else { HttpEntity ent = response.getEntity(); if (ent != null) { String output = EntityUtils.toString(ent); //log(output); JSONObject userInfo = new JSONArray(output).getJSONObject(0); //log("Object: " + userInfo.toString()); if (userInfo.get("workflow").equals("Error")) { log("Upload Error: " + userInfo.get("error")); } else { log("Successful Uploaded. ID is " + userInfo.get("id")); } } } httpClient.close(); } catch (Exception ex) { log("Exception? " + ex.getMessage()); ex.printStackTrace(); // handle exception here } } else { log("Failed to upload!"); } }
From source file:org.flowable.app.service.editor.AppDefinitionPublishService.java
protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey, String deploymentName) {//from ww w. j a va 2 s .co m String deployApiUrl = environment.getRequiredProperty("deployment.api.url"); String basicAuthUser = environment.getRequiredProperty("idm.admin.user"); String basicAuthPassword = environment.getRequiredProperty("idm.admin.password"); if (deployApiUrl.endsWith("/") == false) { deployApiUrl = deployApiUrl.concat("/"); } deployApiUrl = deployApiUrl .concat(String.format("repository/deployments?deploymentKey=%s&deploymentName=%s", encode(deploymentKey), encode(deploymentName))); HttpPost httpPost = new HttpPost(deployApiUrl); httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String( Base64.encodeBase64((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(); SSLConnectionSocketFactory sslsf = null; try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslsf = new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); clientBuilder.setSSLSocketFactory(sslsf); } 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: {}", response.getStatusLine()); 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.kochka.android.weightlogger.tools.GarminConnect.java
public boolean uploadFitFile(File fitFile) { if (httpclient == null) return false; try {/*w w w . ja v a 2 s. c o m*/ HttpPost post = new HttpPost("http://connect.garmin.com/proxy/upload-service-1.1/json/upload/.fit"); /* SimpleMultipartEntity mpEntity = new SimpleMultipartEntity(); mpEntity.addPart("data", fitFile); mpEntity.addPart("responseContentType", "text/html"); post.setEntity(mpEntity); */ MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addBinaryBody("data", fitFile); multipartEntity.addTextBody("responseContentType", "text/html"); post.setEntity(multipartEntity.build()); HttpEntity entity = httpclient.execute(post).getEntity(); JSONObject js_upload = new JSONObject(EntityUtils.toString(entity)); entity.consumeContent(); if (js_upload.getJSONObject("detailedImportResult").getJSONArray("failures").length() != 0) throw new Exception("upload error"); return true; } catch (Exception e) { return false; } }
From source file:org.mule.modules.wechat.common.HttpsConnection.java
public Map<String, Object> postFile(String httpsURL, DataHandler attachment) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(httpsURL); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // Get extension of attachment TikaConfig config = TikaConfig.getDefaultConfig(); MimeTypes allTypes = config.getMimeRepository(); String ext = allTypes.forName(attachment.getContentType()).getExtension(); if (ext.equals("")) { ContentTypeEnum contentTypeEnum = ContentTypeEnum .getContentTypeEnumByContentType(attachment.getContentType().toLowerCase()); ext = java.util.Optional.ofNullable(contentTypeEnum.getExtension()).orElse(""); }/*from ww w. j a va 2 s . co m*/ // Create file InputStream fis = attachment.getInputStream(); byte[] bytes = IOUtils.toByteArray(fis); File f = new File( System.getProperty("user.dir") + "/fileTemp/" + attachment.getName().replace(ext, "") + ext); FileUtils.writeByteArrayToFile(f, bytes); builder.addBinaryBody("media", f); // Post to wechat HttpEntity entity = builder.build(); post.setEntity(entity); CloseableHttpResponse httpResponse = httpClient.execute(post); String content = ""; try { HttpEntity _entity = httpResponse.getEntity(); content = EntityUtils.toString(_entity); EntityUtils.consume(_entity); } finally { httpResponse.close(); } f.delete(); // Convert JSON string to Map ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = mapper.readValue(content, new TypeReference<Map<String, Object>>() { }); return map; }
From source file:org.mule.modules.wechat.common.HttpsConnection.java
public Map<String, Object> postFile(String httpsURL, String title, DataHandler attachment) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(httpsURL); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // Get extension of attachment TikaConfig config = TikaConfig.getDefaultConfig(); MimeTypes allTypes = config.getMimeRepository(); String ext = allTypes.forName(attachment.getContentType()).getExtension(); if (ext.equals("")) { ContentTypeEnum contentTypeEnum = ContentTypeEnum .getContentTypeEnumByContentType(attachment.getContentType().toLowerCase()); ext = java.util.Optional.ofNullable(contentTypeEnum.getExtension()).orElse(""); }// w w w.j a v a2 s.c o m // Create file InputStream fis = attachment.getInputStream(); byte[] bytes = IOUtils.toByteArray(fis); File f = new File(System.getProperty("user.dir") + "/fileTemp/" + title + ext); FileUtils.writeByteArrayToFile(f, bytes); builder.addBinaryBody("media", f); // Post to wechat HttpEntity entity = builder.build(); post.setEntity(entity); CloseableHttpResponse httpResponse = httpClient.execute(post); String content = ""; try { HttpEntity _entity = httpResponse.getEntity(); content = EntityUtils.toString(_entity); EntityUtils.consume(_entity); } finally { httpResponse.close(); } f.delete(); // Convert JSON string to Map ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = mapper.readValue(content, new TypeReference<Map<String, Object>>() { }); return map; }
From source file:org.mule.modules.wechat.common.HttpsConnection.java
public Map<String, Object> postFile(String httpsURL, String title, String introduction, DataHandler attachment) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(httpsURL); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // Get extension of attachment TikaConfig config = TikaConfig.getDefaultConfig(); MimeTypes allTypes = config.getMimeRepository(); String ext = allTypes.forName(attachment.getContentType()).getExtension(); if (ext.equals("")) { ContentTypeEnum contentTypeEnum = ContentTypeEnum .getContentTypeEnumByContentType(attachment.getContentType().toLowerCase()); ext = java.util.Optional.ofNullable(contentTypeEnum.getExtension()).orElse(""); }/*from ww w .j ava 2 s . c om*/ // Create file InputStream fis = attachment.getInputStream(); byte[] bytes = IOUtils.toByteArray(fis); File f = new File(System.getProperty("user.dir") + "/fileTemp/" + title + ext); FileUtils.writeByteArrayToFile(f, bytes); // Create JSON JSONObject obj = new JSONObject(); obj.put("title", title); obj.put("introduction", introduction); ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8")); builder.addBinaryBody("media", f); builder.addTextBody("description", obj.toString(), contentType); // Post to wechat HttpEntity entity = builder.build(); post.setEntity(entity); CloseableHttpResponse httpResponse = httpClient.execute(post); String content = ""; try { HttpEntity _entity = httpResponse.getEntity(); content = EntityUtils.toString(_entity); EntityUtils.consume(_entity); } finally { httpResponse.close(); } f.delete(); // Convert JSON string to Map ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = mapper.readValue(content, new TypeReference<Map<String, Object>>() { }); return map; }
From source file:org.olat.restapi.GroupFoldersTest.java
@Test public void testCreateFoldersWithSpecialCharacter2() throws IOException, URISyntaxException { assertTrue(conn.login("rest-one", "A6B7C8")); URI request = UriBuilder.fromUri(getContextURI()) .path("/groups/" + g1.getKey() + "/folder/New_folder_1/New_folder_1_1/").build(); HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true); HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addTextBody("foldername", "New folder 1 2 3").build(); method.setEntity(entity);/*from w w w . j a v a 2 s . c o m*/ HttpResponse response = conn.execute(method); assertEquals(200, response.getStatusLine().getStatusCode()); FileVO file = conn.parse(response, FileVO.class); assertNotNull(file); assertNotNull(file.getHref()); assertNotNull(file.getTitle()); assertEquals("New folder 1 2 3", file.getTitle()); }
From source file:org.olat.restapi.RestConnection.java
public void addMultipart(HttpEntityEnclosingRequestBase post, String filename, File file) throws UnsupportedEncodingException { HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addTextBody("filename", filename) .addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, filename).build(); post.setEntity(entity);//from w w w .j a va 2s.c om }
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 w w . j a va 2s.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; }