List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder setMode
public MultipartEntityBuilder setMode(final HttpMultipartMode mode)
From source file:io.andyc.papercut.api.PrintApi.java
/** * Uploads the file and finalizes the printing * * @param printJob {PrintJob} - the print job * @param prevElement {Element} - the previous Jsoup element containing the * upload file Html/*w w w .java2 s. co m*/ * * @return {boolean} - whether or not the print job completed */ static boolean uploadFile(PrintJob printJob, Document prevElement) throws PrintingException, UnsupportedMimeTypeException { String uploadUrl = printJob.getSession().getDomain().replace("/app", "") + PrintApi.getUploadFileUrl(prevElement); // upload directory HttpPost post = new HttpPost(uploadUrl); CloseableHttpClient client = HttpClientBuilder.create().build(); // configure multipart post request entity builder MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // build the file boundary String boundary = "-----------------------------" + new Date().getTime(); entityBuilder.setBoundary(boundary); // set the file File file = new File(printJob.getFilePath()); FileBody body = new FileBody(file, ContentType.create(ContentTypes.getApplicationType(printJob.getFilePath())), file.getName()); entityBuilder.addPart("file[]", body); // build the post request HttpEntity multipart = entityBuilder.build(); post.setEntity(multipart); // set cookie post.setHeader("Cookie", printJob.getSession().getSessionKey() + "=" + printJob.getSession().getSession()); // send try { CloseableHttpResponse response = client.execute(post); return response.getStatusLine().getStatusCode() == 200; } catch (IOException e) { throw new PrintingException("Error uploading the file"); } }
From source file:com.codota.uploader.Uploader.java
private void uploadFile(File file, String uploadUrl) throws IOException { HttpPut putRequest = new HttpPut(uploadUrl); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("code", new FileBody(file)); final HttpEntity entity = builder.build(); putRequest.setEntity(entity);// w ww . j av a 2 s . c o m putRequest.setHeader("enctype", "multipart/form-data"); putRequest.setHeader("authorization", "bearer " + token); httpClient.execute(putRequest, new UploadResponseHandler()); }
From source file:org.alfresco.cacheserver.MultipartTest.java
@Test public void test1() throws Exception { byte[] b = "Hello world".getBytes(); InputStream in = new ByteArrayInputStream(b); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).addBinaryBody("p_stream", in) .addTextBody("p_size", String.valueOf(b.length)).addTextBody("p_idx", String.valueOf(10)); HttpEntity entity = builder.build(); entity.writeTo(System.out);//from w w w . java 2 s .co m // BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent())); // while ((inputLine = br.readLine()) != null) { // System.out.println(inputLine); // } // br.close(); // HttpPost httpPost = new HttpPost("http://localhost:2389/TESTME_WITH_NETCAT"); // httpPost.setEntity(entity); }
From source file:com.kurento.test.recorder.RecorderIT.java
private void testRecord(String handler, int statusCode) throws IOException { // To follow redirect: .setRedirectStrategy(new LaxRedirectStrategy()) HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost("http://localhost:" + getServerPort() + "/kmf-content-api-test/" + handler); MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); File file = new File("small"); URL small = new URL(VideoURLs.map.get("small-webm")); FileUtils.copyURLToFile(small, file); FileBody fb = new FileBody(file); multipartEntity.addPart("file", fb); HttpEntity httpEntity = multipartEntity.build(); post.setEntity(httpEntity);//ww w . jav a 2 s . co m EntityUtils.consume(httpEntity); HttpResponse response = client.execute(post); final int responseStatusCode = response.getStatusLine().getStatusCode(); log.info("Response Status Code: {}", responseStatusCode); log.info("Deleting tmp file: {}", file.delete()); Assert.assertEquals("HTTP response status code must be " + statusCode, statusCode, responseStatusCode); }
From source file:org.apache.heron.uploader.http.HttpUploader.java
private URI uploadPackageAndGetURI(final CloseableHttpClient httpclient) throws IOException, URISyntaxException { File file = new File(this.topologyPackageLocation); String uploaderUri = HttpUploaderContext.getHeronUploaderHttpUri(this.config); post = new HttpPost(uploaderUri); FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart(FILE, fileBody);//from ww w .ja v a 2 s . c o m HttpEntity entity = builder.build(); post.setEntity(entity); HttpResponse response = execute(httpclient); String responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8.name()); LOG.fine("Topology package download URI: " + responseString); return new URI(responseString); }
From source file:org.uberfire.provisioning.wildfly.runtime.provider.extras.Wildfly10RemoteClient.java
public int deploy(String user, String password, String host, int port, String filePath) { // the digest auth backend CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(user, password)); CloseableHttpClient httpclient = custom().setDefaultCredentialsProvider(credsProvider).build(); HttpPost post = new HttpPost("http://" + host + ":" + port + "/management-upload"); post.addHeader("X-Management-Client-Name", "HAL"); // the file to be uploaded File file = new File(filePath); FileBody fileBody = new FileBody(file); // the DMR operation ModelNode operation = new ModelNode(); operation.get("address").add("deployment", file.getName()); operation.get("operation").set("add"); operation.get("runtime-name").set(file.getName()); operation.get("enabled").set(true); operation.get("content").add().get("input-stream-index").set(0); // point to the multipart index used ByteArrayOutputStream bout = new ByteArrayOutputStream(); try {/* ww w . j a v a2 s. c o m*/ operation.writeBase64(bout); } catch (IOException ex) { getLogger(Wildfly10RemoteClient.class.getName()).log(SEVERE, null, ex); } // the multipart MultipartEntityBuilder builder = create(); builder.setMode(BROWSER_COMPATIBLE); builder.addPart("uploadFormElement", fileBody); builder.addPart("operation", new ByteArrayBody(bout.toByteArray(), create("application/dmr-encoded"), "blob")); HttpEntity entity = builder.build(); //entity.writeTo(System.out); post.setEntity(entity); try { HttpResponse response = httpclient.execute(post); out.println(">>> Deploying Response Entity: " + response.getEntity()); out.println(">>> Deploying Response Satus: " + response.getStatusLine().getStatusCode()); return response.getStatusLine().getStatusCode(); } catch (IOException ex) { ex.printStackTrace(); getLogger(Wildfly10RemoteClient.class.getName()).log(SEVERE, null, ex); } return -1; }
From source file:com.neighbor.ex.tong.network.UploadFileAndMessage.java
@Override protected Void doInBackground(Void... voids) { try {//www . ja v a2 s. c o m MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addTextBody("message", URLEncoder.encode(message, "UTF-8"), ContentType.create("Multipart/related", "UTF-8")); builder.addPart("image", new FileBody(new File(path))); InputStream inputStream = null; HttpClient httpClient = AndroidHttpClient.newInstance("Android"); String carNo = prefs.getString(CONST.ACCOUNT_LICENSE, ""); String encodeCarNo = ""; if (false == carNo.equals("")) { encodeCarNo = URLEncoder.encode(carNo, "UTF-8"); } HttpPost httpPost = new HttpPost(UPLAOD_URL + encodeCarNo); httpPost.setEntity(builder.build()); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); inputStream = httpEntity.getContent(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); StringBuilder stringBuilder = new StringBuilder(); String line = null; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line + "\n"); } inputStream.close(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:org.retrostore.data.BlobstoreWrapperImpl.java
@Override public void addScreenshot(String appId, byte[] data, Responder.ContentType contentType, String cookie) { Preconditions.checkArgument(!Strings.isNullOrEmpty(appId), "'appId' missing"); Preconditions.checkArgument(data != null && data.length > 0, "'data' is empty"); Preconditions.checkNotNull(contentType, "'contentType' missing"); Preconditions.checkArgument(!Strings.isNullOrEmpty(cookie), "'cookie' missing"); LOG.info(String.format("About to add a screenshot blob of size %d with type %s.", data.length, contentType.str));/*from ww w . j a v a 2 s . co m*/ final String PATH_UPLOAD = "/screenshotUpload"; String forwardTo = PATH_UPLOAD + "?appId=" + appId; LOG.info("Forward to: " + forwardTo); String uploadUrl = createUploadUrl(forwardTo); LOG.info("UploadUrl: " + uploadUrl); // It is important that we set the cookie so that we're authenticated. We do not allow // anonymous requests to upload screenshots. HttpPost post = new HttpPost(uploadUrl); post.setHeader("Cookie", cookie); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // Note we need to use the deprecated constructor so we can use our content type. builder.addPart("file", new ByteArrayBody(data, contentType.str, "screenshot")); HttpEntity entity = builder.build(); post.setEntity(entity); HttpClient client = HttpClientBuilder.create().build(); try { LOG.info("POST constructed. About to make request!"); HttpResponse response = client.execute(post); LOG.info("Request succeeded!"); ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); LOG.info(new String(out.toByteArray(), "UTF-8")); } catch (IOException e) { LOG.log(Level.SEVERE, "Cannot make POST request.", e); } }
From source file:org.ow2.proactive_grid_cloud_portal.rm.server.serialization.CatalogRequestBuilder.java
protected HttpPost buildCatalogRequest(String fullUri) { String boundary = "---------------" + UUID.randomUUID().toString(); HttpPost post = new HttpPost(fullUri); post.addHeader("Accept", "application/json"); post.addHeader("Content-Type", org.apache.http.entity.ContentType.MULTIPART_FORM_DATA.getMimeType() + ";boundary=" + boundary); post.addHeader("sessionId", this.catalogObjectAction.getSessionId()); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setBoundary(boundary);//from w ww . j a v a 2 s . co m builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("file", new FileBody(this.catalogObjectAction.getNodeSourceJsonFile())); builder.addTextBody(COMMIT_MESSAGE_PARAM, this.catalogObjectAction.getCommitMessage()); if (!this.catalogObjectAction.isRevised()) { builder.addTextBody(NAME_PARAM, this.catalogObjectAction.getNodeSourceName()); builder.addTextBody(KIND_PARAM, this.catalogObjectAction.getKind()); builder.addTextBody(OBJECT_CONTENT_TYPE_PARAM, this.catalogObjectAction.getObjectContentType()); } post.setEntity(builder.build()); return post; }
From source file:Vdisk.java
public void upload_file(String local_filepath, String filepath) throws URISyntaxException, FileNotFoundException, IOException { File file = new File(local_filepath); URI uri = new URIBuilder().setScheme("http").setHost("upload-vdisk.sina.com.cn/2/files/sandbox/") .setPath(filepath).setParameter("access_token", this.access_token).build(); HttpPost httpPost = new HttpPost(uri); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, local_filepath); HttpEntity entity = builder.build(); httpPost.setEntity(entity);/*from ww w . ja va2 s . co m*/ CloseableHttpClient postClient = HttpClients.createDefault(); try (CloseableHttpResponse response = postClient.execute(httpPost)) { System.out.println(response);//check result } finally { postClient.close(); } }