List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder create
public static MultipartEntityBuilder create()
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);// w ww .j a v a2 s . com // 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:poisondog.net.ApacheHttpPost.java
public ApacheHttpPost() { mHttpClient = HttpClientBuilder.create().build(); mBuilder = MultipartEntityBuilder.create(); }
From source file:org.rapidoid.http.HTTP.java
public static byte[] post(String uri, Map<String, String> headers, Map<String, String> data, Map<String, String> files) throws IOException, ClientProtocolException { headers = U.safe(headers);// w ww .j a v a 2s . c o m data = U.safe(data); files = U.safe(files); CloseableHttpClient client = client(uri); try { HttpPost httppost = new HttpPost(uri); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (Entry<String, String> entry : files.entrySet()) { ContentType contentType = ContentType.create("application/octet-stream"); String filename = entry.getValue(); File file = IO.file(filename); builder = builder.addBinaryBody(entry.getKey(), file, contentType, filename); } for (Entry<String, String> entry : data.entrySet()) { ContentType contentType = ContentType.create("text/plain", "UTF-8"); builder = builder.addTextBody(entry.getKey(), entry.getValue(), contentType); } httppost.setEntity(builder.build()); for (Entry<String, String> e : headers.entrySet()) { httppost.addHeader(e.getKey(), e.getValue()); } Log.info("Starting HTTP POST request", "request", httppost.getRequestLine()); CloseableHttpResponse response = client.execute(httppost); try { int statusCode = response.getStatusLine().getStatusCode(); U.must(statusCode == 200, "Expected HTTP status code 200, but found: %s", statusCode); InputStream resp = response.getEntity().getContent(); return IOUtils.toByteArray(resp); } finally { response.close(); } } finally { client.close(); } }
From source file:org.camunda.bpm.ext.sdk.DeploymentBuilder.java
public DeploymentBuilder(ClientCommandExecutor commandExecutor) { requestBuilder = MultipartEntityBuilder.create(); this.commandExecutor = commandExecutor; }
From source file:groovyx.net.http.ApacheEncoders.java
/** * Encodes multipart/form-data where the body content must be an instance of the {@link MultipartContent} class. Individual parts will be * encoded using the encoders available to the {@link ChainedHttpConfig} object. * * @param config the chained configuration object * @param ts the server adapter//from w w w. j a v a 2 s . c o m */ public static void multipart(final ChainedHttpConfig config, final ToServer ts) { try { final ChainedHttpConfig.ChainedRequest request = config.getChainedRequest(); final Object body = request.actualBody(); if (!(body instanceof MultipartContent)) { throw new IllegalArgumentException("Multipart body content must be MultipartContent."); } final String contentType = request.actualContentType(); if (!(contentType.equals(MULTIPART_FORMDATA.getAt(0)) || contentType.equals(MULTIPART_MIXED.getAt(0)))) { throw new IllegalArgumentException("Multipart body content must be multipart/form-data."); } final String boundary = randomString(10); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().setBoundary(boundary); final String boundaryContentType = "multipart/form-data; boundary=" + boundary; entityBuilder.setContentType(ContentType.parse(boundaryContentType)); for (final MultipartContent.MultipartPart mpe : ((MultipartContent) body).parts()) { if (mpe.getFileName() == null) { entityBuilder.addTextBody(mpe.getFieldName(), (String) mpe.getContent()); } else { final byte[] encodedBytes = EmbeddedEncoder.encode(config, mpe.getContentType(), mpe.getContent()); entityBuilder.addBinaryBody(mpe.getFieldName(), encodedBytes, parse(mpe.getContentType()), mpe.getFileName()); } } request.setContentType(boundaryContentType); ts.toServer(entityBuilder.build().getContent()); } catch (IOException ioe) { ioe.printStackTrace(); } }
From source file:com.afrisoftech.lib.PDF2ExcelConverter.java
public static void convertPDf2Excel(String pdfFile2Convert) throws Exception { if (pdfFile2Convert.length() < 3) { System.out.println("File to convert is mandatory!"); javax.swing.JOptionPane.showMessageDialog(null, "File to convert is mandatory!"); } else {/*from www . j av a2s. c o m*/ final String apiKey = "ktxpfvf0i5se"; final String format = "xlsx-single".toLowerCase(); final String pdfFilename = pdfFile2Convert; if (!formats.contains(format)) { System.out.println("Invalid output format: \"" + format + "\""); } // Avoid cookie warning with default cookie configuration RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build(); File inputFile = new File(pdfFilename); if (!inputFile.canRead()) { System.out.println("Can't read input PDF file: \"" + pdfFilename + "\""); javax.swing.JOptionPane.showMessageDialog(null, "File to convert is mandatory!"); } try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .build()) { HttpPost httppost = new HttpPost("https://pdftables.com/api?format=" + format + "&key=" + apiKey); FileBody fileBody = new FileBody(inputFile); HttpEntity requestBody = MultipartEntityBuilder.create().addPart("f", fileBody).build(); httppost.setEntity(requestBody); System.out.println("Sending request"); try (CloseableHttpResponse response = httpclient.execute(httppost)) { if (response.getStatusLine().getStatusCode() != 200) { System.out.println(response.getStatusLine()); javax.swing.JOptionPane.showMessageDialog(null, "Internet connection is a must. Consult IT administrator for further assistance"); } HttpEntity resEntity = response.getEntity(); if (resEntity != null) { final String outputFilename = getOutputFilename(pdfFilename, format.replaceFirst("-.*$", "")); System.out.println("Writing output to " + outputFilename); final File outputFile = new File(outputFilename); FileUtils.copyInputStreamToFile(resEntity.getContent(), outputFile); if (java.awt.Desktop.isDesktopSupported()) { try { java.awt.Desktop.getDesktop().open(outputFile); } catch (IOException ex) { javax.swing.JOptionPane.showMessageDialog(new java.awt.Frame(), ex.getMessage()); ex.printStackTrace(); //Exceptions.printStackTrace(ex); } } } else { System.out.println("Error: file missing from response"); javax.swing.JOptionPane.showMessageDialog(null, "Error: file missing from response! Internet connection is a must."); } } } } }
From source file:com.portfolio.data.utils.PostForm.java
public static boolean sendFile(String sessionid, String backend, String user, String uuid, String lang, File file) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try {//from w ww .j a v a2 s.co m // Server + "/resources/resource/file/" + uuid +"?lang="+ lang // "http://"+backend+"/user/"+user+"/file/"+uuid+"/"+lang+"ptype/fs"; String url = "http://" + backend + "/resources/resource/file/" + uuid + "?lang=" + lang; HttpPost post = new HttpPost(url); post.setHeader("Cookie", "JSESSIONID=" + sessionid); // So that the receiving servlet allow us /// Remove import language tag String filename = file.getName(); /// NOTE: Since it's used with zip import, specific code. int langindex = filename.lastIndexOf("_"); filename = filename.substring(0, langindex) + filename.substring(langindex + 3); FileBody bin = new FileBody(file, ContentType.DEFAULT_BINARY, filename); // File from import /// Form info HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("uploadfile", bin).build(); post.setEntity(reqEntity); CloseableHttpResponse response = httpclient.execute(post); /* try { HttpEntity resEntity = response.getEntity(); /// Will be JSON if( resEntity != null ) { BufferedReader reader = new BufferedReader(new InputStreamReader(resEntity.getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); for( String line = null; (line = reader.readLine()) != null; ) builder.append(line).append("\n"); updateResource( sessionid, backend, uuid, lang, builder.toString() ); } EntityUtils.consume(resEntity); } finally { response.close(); } //*/ } finally { httpclient.close(); } return true; }
From source file:com.neighbor.ex.tong.network.UploadFileAndMessage.java
@Override protected Void doInBackground(Void... voids) { try {/*from www .j ava 2 s. co 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:core.VirusTotalAPIHelper.java
public static CloseableHttpResponse getReport(String sha256) { try {//w w w .j a va 2 s. c o m CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpsScanFilePost = new HttpPost(httpsPost + "file/report"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("apikey", apiKey); builder.addTextBody("resource", sha256); HttpEntity multipart = builder.build(); httpsScanFilePost.setEntity(multipart); CloseableHttpResponse response = client.execute(httpsScanFilePost); return response; } catch (IOException ex) { Exceptions.printStackTrace(ex); } return null; }