List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder setMode
public MultipartEntityBuilder setMode(final HttpMultipartMode mode)
From source file:com.osbitools.ws.shared.web.BasicWebUtils.java
public WebResponse uploadFile(String path, String fname, InputStream in, String stoken) throws ClientProtocolException, IOException { HttpPost post = new HttpPost(path); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); StringBody fn = new StringBody(fname, ContentType.MULTIPART_FORM_DATA); builder.addPart("fname", fn); builder.addBinaryBody("file", in, ContentType.APPLICATION_XML, fname); BasicCookieStore cookieStore = new BasicCookieStore(); if (stoken != null) { BasicClientCookie cookie = new BasicClientCookie(Constants.SECURE_TOKEN_NAME, stoken); cookie.setDomain(TestConstants.JETTY_HOST); cookie.setPath("/"); cookieStore.addCookie(cookie);//ww w . j a va2s . com } TestConstants.LOG.debug("stoken=" + stoken); HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build(); HttpEntity entity = builder.build(); post.setEntity(entity); HttpResponse response = client.execute(post); String body; ResponseHandler<String> handler = new BasicResponseHandler(); try { body = handler.handleResponse(response); } catch (HttpResponseException e) { return new WebResponse(e.getStatusCode(), e.getMessage()); } return new WebResponse(response.getStatusLine().getStatusCode(), body); }
From source file:org.syncany.plugins.php.PhpTransferManager.java
@Override public void upload(File localFile, RemoteFile remoteFile) throws StorageException { logger.info("Uploading: " + localFile.getName() + " to " + remoteFile.getName()); try {//from w ww. ja va2s . c o m final String remote_name = remoteFile.getName(); final File f = localFile; int r = operate("upload", new IPost() { List<NameValuePair> _nvps; public void mutateNVPS(List<NameValuePair> nvps) throws Exception { _nvps = nvps; nvps.add(new BasicNameValuePair("filename", remote_name)); } public int mutatePost(HttpPost p) throws Exception { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("file", new FileBody(f)); Iterator<NameValuePair> it = _nvps.iterator(); while (it.hasNext()) { NameValuePair nvp = it.next(); builder.addTextBody(nvp.getName(), nvp.getValue()); } p.setEntity(builder.build()); return -1; } @Override public int consumeResponse(InputStream s) throws Exception { String response = getAnswer(s); if (response.equals("true")) { return 1; } else { throw new Exception(response); } } }); if (r != 1) { throw new Exception("Unexpected error, result code = " + r); } } catch (Exception e) { throw new StorageException("Cannot upload file " + remoteFile, e); } }
From source file:com.adobe.aem.demo.communities.Loader.java
private static String doThumbnail(String hostname, String port, String adminPassword, String csvfile, String filename) {/*from ww w. ja v a 2 s . c om*/ String pathToFile = "/content/dam/communities/resource-thumbnails/" + filename; File attachment = new File(csvfile.substring(0, csvfile.indexOf(".csv")) + File.separator + filename); ContentType ct = ContentType.MULTIPART_FORM_DATA; if (filename.indexOf(".mp4") > 0) { ct = ContentType.create("video/mp4", MIME.UTF8_CHARSET); } else if (filename.indexOf(".jpg") > 0 || filename.indexOf(".jpeg") > 0) { ct = ContentType.create("image/jpeg", MIME.UTF8_CHARSET); } else if (filename.indexOf(".png") > 0) { ct = ContentType.create("image/png", MIME.UTF8_CHARSET); } MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setCharset(MIME.UTF8_CHARSET); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addBinaryBody("file", attachment, ct, attachment.getName()); builder.addTextBody("fileName", filename, ContentType.create("text/plain", MIME.UTF8_CHARSET)); logger.debug( "Adding file for thumbnails with name: " + attachment.getName() + " and type: " + ct.getMimeType()); Loader.doPost(hostname, port, pathToFile, "admin", adminPassword, builder.build(), null); logger.debug("Path to thumbnail: " + pathToFile); return pathToFile + "/file"; }
From source file:com.ebixio.virtmus.stats.StatsLogger.java
/** Should only be called from uploadLogs(). Compresses all files that belong to the given log set, and uploads all compressed files to the server. */ private boolean uploadLogs(final String logSet) { if (logSet == null) return false; File logsDir = getLogsDir();// w w w. j a v a 2s .c o m if (logsDir == null) return false; gzipLogs(logsDir, logSet); // Uploading only gz'd files FilenameFilter gzFilter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".gz"); } }; File[] toUpload = logsDir.listFiles(gzFilter); String url = getUploadUrl(); if (url == null) { /* This means the server is unable to accept the logs. */ keepRecents(toUpload, 100); return false; } CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(url); addHttpHeaders(post); MultipartEntityBuilder entity = MultipartEntityBuilder.create(); entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("InstallId", new StringBody(String.valueOf(MainApp.getInstallId()), ContentType.TEXT_PLAIN)); ContentType ct = ContentType.create("x-application/gzip"); for (File f : toUpload) { entity.addPart("VirtMusStats", new FileBody(f, ct, f.getName())); } post.setEntity(entity.build()); boolean success = false; try (CloseableHttpResponse response = client.execute(post)) { int status = response.getStatusLine().getStatusCode(); Log.log(Level.INFO, "Log upload result: {0}", status); if (status == HttpStatus.SC_OK) { // 200 for (File f : toUpload) { try { f.delete(); } catch (SecurityException ex) { } } success = true; } else { LogRecord rec = new LogRecord(Level.INFO, "Server Err"); rec.setParameters(new Object[] { url, "Status: " + status }); getLogger().log(rec); } HttpEntity rspEntity = response.getEntity(); EntityUtils.consume(rspEntity); client.close(); } catch (IOException ex) { Log.log(ex); } keepRecents(toUpload, 100); // In case of exceptions or errors return success; }
From source file:com.basistech.rosette.api.HttpRosetteAPI.java
private void setupMultipartRequest(final Request request, final ObjectWriter finalWriter, HttpPost post) throws IOException { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMimeSubtype("mixed"); builder.setMode(HttpMultipartMode.STRICT); FormBodyPartBuilder partBuilder = FormBodyPartBuilder.create("request", // Make sure we're not mislead by someone who puts a charset into the mime type. new AbstractContentBody(ContentType.parse(ContentType.APPLICATION_JSON.getMimeType())) { @Override//w ww . j av a 2 s . co m public String getFilename() { return null; } @Override public void writeTo(OutputStream out) throws IOException { finalWriter.writeValue(out, request); } @Override public String getTransferEncoding() { return MIME.ENC_BINARY; } @Override public long getContentLength() { return -1; } }); // Either one of 'name=' or 'Content-ID' would be enough. partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"request\""); partBuilder.setField("Content-ID", "request"); builder.addPart(partBuilder.build()); AbstractContentBody insBody; if (request instanceof DocumentRequest) { DocumentRequest docReq = (DocumentRequest) request; insBody = new InputStreamBody(docReq.getContentBytes(), ContentType.parse(docReq.getContentType())); } else if (request instanceof AdmRequest) { //TODO: smile? AdmRequest admReq = (AdmRequest) request; ObjectWriter writer = mapper.writer().without(JsonGenerator.Feature.AUTO_CLOSE_TARGET); byte[] json = writer.writeValueAsBytes(admReq.getText()); insBody = new ByteArrayBody(json, ContentType.parse(AdmRequest.ADM_CONTENT_TYPE), null); } else { throw new UnsupportedOperationException("Unsupported request type for multipart processing"); } partBuilder = FormBodyPartBuilder.create("content", insBody); partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"content\""); partBuilder.setField("Content-ID", "content"); builder.addPart(partBuilder.build()); builder.setCharset(StandardCharsets.UTF_8); HttpEntity entity = builder.build(); post.setEntity(entity); }
From source file:org.archive.modules.fetcher.FetchHTTPRequest.java
protected HttpEntity buildPostRequestEntity(CrawlURI curi) { String enctype = (String) curi.getData().get(CoreAttributeConstants.A_SUBMIT_ENCTYPE); if (enctype == null) { enctype = ContentType.APPLICATION_FORM_URLENCODED.getMimeType(); }/* w w w . j a v a2 s .c om*/ @SuppressWarnings("unchecked") List<NameValue> submitData = (List<NameValue>) curi.getData().get(CoreAttributeConstants.A_SUBMIT_DATA); if (enctype.equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) { LinkedList<NameValuePair> nvps = new LinkedList<NameValuePair>(); for (NameValue nv : submitData) { nvps.add(new BasicNameValuePair(nv.name, nv.value)); } try { return new UrlEncodedFormEntity(nvps, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } else if (enctype.equals(ContentType.MULTIPART_FORM_DATA.getMimeType())) { MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (NameValue nv : submitData) { entityBuilder.addTextBody(escapeForMultipart(nv.name), escapeForMultipart(nv.value)); } return entityBuilder.build(); } else { throw new IllegalStateException("unsupported form submission enctype='" + enctype + "'"); } }
From source file:com.buffalokiwi.api.API.java
/** * Perform a post-based request to some endpoint * @param url The URL//from w w w. j av a2 s .c o m * @param formData Key/Value pairs to send * @param files Key/File files to send * @param headers Extra headers to send * @return response * @throws APIException If something goes wrong */ @Override public IAPIResponse post(final String url, final List<NameValuePair> formData, final Map<String, PostFile> files, final Map<String, String> headers) throws APIException { final HttpPost post = (HttpPost) createRequest(HttpMethod.POST, url, headers); //..Create a multi-part form data entity final MultipartEntityBuilder b = MultipartEntityBuilder.create(); //..Set the mode b.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); setMultipartFileData(files, b); //..Check for non-file form data setMultipartFormData(formData, b); //..Attach the form data to the post request post.setEntity(b.build()); //..Execute the request return executeRequest(post); }