List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder addBinaryBody
public MultipartEntityBuilder addBinaryBody(final String name, final InputStream stream, final ContentType contentType, final String filename)
From source file:com.adobe.ags.curly.controller.ActionRunner.java
private void addPostParams(HttpEntityEnclosingRequestBase request) throws UnsupportedEncodingException { final MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create(); List<NameValuePair> formParams = new ArrayList<>(); postVariables.forEach((name, values) -> values.forEach(value -> { if (multipart) { if (value.startsWith("@")) { File f = new File(value.substring(1)); multipartBuilder.addBinaryBody(name, f, ContentType.DEFAULT_BINARY, f.getName()); } else { multipartBuilder.addTextBody(name, value); }/* ww w .ja v a 2s.co m*/ } else { formParams.add(new BasicNameValuePair(name, value)); } })); if (multipart) { request.setEntity(multipartBuilder.build()); } else { request.setEntity(new UrlEncodedFormEntity(formParams)); } }
From source file:be.samey.io.ServerConn.java
private HttpEntity makeEntity(String baits, String[] names, Path[] filepaths, double poscutoff, double negcutoff, String[] orthNames, Path[] orthPaths) throws UnsupportedEncodingException { MultipartEntityBuilder mpeb = MultipartEntityBuilder.create(); //make hidden form fields, to the server knows to use the api mpeb.addPart("__controller", new StringBody("api")); mpeb.addPart("__action", new StringBody("execute_job")); //make the bait part StringBody baitspart = new StringBody(baits, ContentType.TEXT_PLAIN); mpeb.addPart("baits", baitspart); //make the species file upload parts for (int i = 0; i < CyModel.MAX_SPECIES_COUNT; i++) { if (i < names.length && i < filepaths.length) { mpeb.addBinaryBody("matrix[]", filepaths[i].toFile(), ContentType.TEXT_PLAIN, names[i]); }/*from w w w . j a va 2 s . co m*/ } //make the cutoff parts StringBody poscpart = new StringBody(Double.toString(poscutoff)); mpeb.addPart("positive_correlation", poscpart); StringBody negcpart = new StringBody(Double.toString(negcutoff)); mpeb.addPart("negative_correlation", negcpart); //make the orthgroup file upload parts for (int i = 0; i < CyModel.MAX_ORTHGROUP_COUNT; i++) { if (cyModel.getOrthGroupPaths() != null && i < orthNames.length && i < orthPaths.length) { mpeb.addBinaryBody("orthologs[]", orthPaths[i].toFile(), ContentType.TEXT_PLAIN, orthNames[i]); } } return mpeb.build(); }
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);/*from w w w. ja v a 2s. c o m*/ } 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:com.adobe.aem.demo.communities.Loader.java
private static String doThumbnail(String hostname, String port, String adminPassword, String csvfile, String filename) {// w w w . ja va2 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:hspc.submissionsprogram.AppDisplay.java
AppDisplay() { this.setTitle("Dominion High School Programming Contest"); this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); this.setResizable(false); WindowListener exitListener = new WindowAdapter() { @Override/*from ww w . j a v a2s.co m*/ public void windowClosing(WindowEvent e) { System.exit(0); } }; this.addWindowListener(exitListener); JTabbedPane pane = new JTabbedPane(); this.add(pane); JPanel submitPanel = new JPanel(null); submitPanel.setPreferredSize(new Dimension(500, 500)); UIManager.put("FileChooser.readOnly", true); JFileChooser fileChooser = new JFileChooser(); fileChooser.setBounds(0, 0, 500, 350); fileChooser.setVisible(true); FileNameExtensionFilter javaFilter = new FileNameExtensionFilter("Java files (*.java)", "java"); fileChooser.setFileFilter(javaFilter); fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.setControlButtonsAreShown(false); submitPanel.add(fileChooser); JSeparator separator1 = new JSeparator(); separator1.setBounds(12, 350, 476, 2); separator1.setForeground(new Color(122, 138, 152)); submitPanel.add(separator1); JLabel problemChooserLabel = new JLabel("Problem:"); problemChooserLabel.setBounds(12, 360, 74, 25); submitPanel.add(problemChooserLabel); String[] listOfProblems = Main.Configuration.get("problem_names") .split(Main.Configuration.get("name_delimiter")); JComboBox problems = new JComboBox<>(listOfProblems); problems.setBounds(96, 360, 393, 25); submitPanel.add(problems); JButton submit = new JButton("Submit"); submit.setBounds(170, 458, 160, 30); submit.addActionListener(e -> { try { File file = fileChooser.getSelectedFile(); try { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost uploadFile = new HttpPost(Main.Configuration.get("submit_url")); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("accountID", Main.accountID, ContentType.TEXT_PLAIN); builder.addTextBody("problem", String.valueOf(problems.getSelectedItem()), ContentType.TEXT_PLAIN); builder.addBinaryBody("submission", file, ContentType.APPLICATION_OCTET_STREAM, file.getName()); HttpEntity multipart = builder.build(); uploadFile.setEntity(multipart); CloseableHttpResponse response = httpClient.execute(uploadFile); HttpEntity responseEntity = response.getEntity(); String inputLine; BufferedReader br = new BufferedReader(new InputStreamReader(responseEntity.getContent())); try { if ((inputLine = br.readLine()) != null) { int rowIndex = Integer.parseInt(inputLine); new ResultWatcher(rowIndex); } br.close(); } catch (IOException ex) { ex.printStackTrace(); } } catch (Exception ex) { ex.printStackTrace(); } } catch (NullPointerException ex) { JOptionPane.showMessageDialog(this, "No file selected.\nPlease select a java file.", "Error", JOptionPane.WARNING_MESSAGE); } }); submitPanel.add(submit); JPanel clarificationsPanel = new JPanel(null); clarificationsPanel.setPreferredSize(new Dimension(500, 500)); cList = new JList<>(); cList.setBounds(12, 12, 476, 200); cList.setBorder(new CompoundBorder(BorderFactory.createLineBorder(new Color(122, 138, 152)), BorderFactory.createEmptyBorder(8, 8, 8, 8))); cList.setBackground(new Color(254, 254, 255)); clarificationsPanel.add(cList); JButton viewC = new JButton("View"); viewC.setBounds(12, 224, 232, 25); viewC.addActionListener(e -> { if (cList.getSelectedIndex() != -1) { int id = Integer.parseInt(cList.getSelectedValue().split("\\.")[0]); clarificationDatas.stream().filter(data -> data.getId() == id).forEach( data -> new ClarificationDisplay(data.getProblem(), data.getText(), data.getResponse())); } }); clarificationsPanel.add(viewC); JButton refreshC = new JButton("Refresh"); refreshC.setBounds(256, 224, 232, 25); refreshC.addActionListener(e -> updateCList(true)); clarificationsPanel.add(refreshC); JSeparator separator2 = new JSeparator(); separator2.setBounds(12, 261, 476, 2); separator2.setForeground(new Color(122, 138, 152)); clarificationsPanel.add(separator2); JLabel problemChooserLabelC = new JLabel("Problem:"); problemChooserLabelC.setBounds(12, 273, 74, 25); clarificationsPanel.add(problemChooserLabelC); JComboBox problemsC = new JComboBox<>(listOfProblems); problemsC.setBounds(96, 273, 393, 25); clarificationsPanel.add(problemsC); JTextArea textAreaC = new JTextArea(); textAreaC.setLineWrap(true); textAreaC.setWrapStyleWord(true); textAreaC.setBorder(new CompoundBorder(BorderFactory.createLineBorder(new Color(122, 138, 152)), BorderFactory.createEmptyBorder(8, 8, 8, 8))); textAreaC.setBackground(new Color(254, 254, 255)); JScrollPane areaScrollPane = new JScrollPane(textAreaC); areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); areaScrollPane.setBounds(12, 312, 477, 134); clarificationsPanel.add(areaScrollPane); JButton submitC = new JButton("Submit Clarification"); submitC.setBounds(170, 458, 160, 30); submitC.addActionListener(e -> { if (textAreaC.getText().length() > 2048) { JOptionPane.showMessageDialog(this, "Clarification body is too long.\nMaximum of 2048 characters allowed.", "Error", JOptionPane.WARNING_MESSAGE); } else if (textAreaC.getText().length() < 20) { JOptionPane.showMessageDialog(this, "Clarification body is too short.\nClarifications must be at least 20 characters, but no more than 2048.", "Error", JOptionPane.WARNING_MESSAGE); } else { Connection conn = null; PreparedStatement stmt = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(Main.Configuration.get("jdbc_mysql_address"), Main.Configuration.get("mysql_user"), Main.Configuration.get("mysql_pass")); String sql = "INSERT INTO clarifications (team, problem, text) VALUES (?, ?, ?)"; stmt = conn.prepareStatement(sql); stmt.setInt(1, Integer.parseInt(String.valueOf(Main.accountID))); stmt.setString(2, String.valueOf(problemsC.getSelectedItem())); stmt.setString(3, String.valueOf(textAreaC.getText())); textAreaC.setText(""); stmt.executeUpdate(); stmt.close(); conn.close(); updateCList(false); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (stmt != null) { stmt.close(); } } catch (Exception ex2) { ex2.printStackTrace(); } try { if (conn != null) { conn.close(); } } catch (Exception ex2) { ex2.printStackTrace(); } } } }); clarificationsPanel.add(submitC); pane.addTab("Submit", submitPanel); pane.addTab("Clarifications", clarificationsPanel); Timer timer = new Timer(); TimerTask updateTask = new TimerTask() { @Override public void run() { updateCList(false); } }; timer.schedule(updateTask, 10000, 10000); updateCList(false); this.pack(); this.setLocationRelativeTo(null); this.setVisible(true); }
From source file:com.licryle.httpposter.HttpPoster.java
/** * Builds the {@link _ProgressiveEntity} that we will send to the server. * Takes for input an {@link HttpConfiguration} that contains the Post * variables and File Names to send./* w ww .ja va2s.co m*/ * * @param mConf Configuration of the POST request to be processed. * @return A ProgressiveEntity which progress can be tracked as we send it to * the server. * * @throws IOException When a file in the list of files from * {@link HttpConfiguration#getFiles()} cannot be read. * * @see {@link com.licryle.httpposter.HttpPoster._ProgressiveEntity} * @see {@link com.licryle.httpposter.HttpConfiguration} */ protected _ProgressiveEntity _buildEntity(HttpConfiguration mConf) throws IOException { Log.d("HttpPoster", String.format("_buildEntity: Entering for Instance %d", _iInstanceId)); /********* Build request content *********/ MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create(); mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); mBuilder.setBoundary(mConf.getHTTPBoundary()); int iFileNb = 0; Iterator mFiles = mConf.getFiles().iterator(); while (mFiles.hasNext()) { final File mFile = (File) mFiles.next(); try { mBuilder.addBinaryBody("file_" + iFileNb, mFile, ContentType.DEFAULT_BINARY, mFile.getName()); } catch (Exception e) { throw new IOException(); } iFileNb++; } Iterator mArgs = mConf.getArgs().entrySet().iterator(); while (mArgs.hasNext()) { Map.Entry mPair = (Map.Entry) mArgs.next(); mBuilder.addTextBody((String) mPair.getKey(), (String) mPair.getValue(), ContentType.MULTIPART_FORM_DATA); } Log.d("HttpPoster", String.format("_buildEntity: Leaving for Instance %d", _iInstanceId)); return new _ProgressiveEntity(mBuilder.build(), this); }
From source file:com.tur0kk.facebook.FacebookClient.java
public String publishPicture(String msg, Image image, String placeId) throws IOException { OAuthRequest request = new OAuthRequest(Verb.POST, "https://graph.facebook.com/v2.2/me/photos"); // request node request.addHeader("Authorization", "Bearer " + accesTokenString); // authentificate // check input to avoid error responses if (msg != null && image != null) { // facebook requires multipart post structure MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("message", msg); // description if (placeId != null && !"".equals(placeId)) { builder.addTextBody("place", placeId); // add link to FabLab site if property is set in preferences }/*from w ww . jav a2 s. c o m*/ // convert image to bytearray and append to multipart BufferedImage bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D bGr = bimage.createGraphics(); bGr.drawImage(image, 0, 0, null); bGr.dispose(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bimage, "png", baos); builder.addBinaryBody(msg, baos.toByteArray(), ContentType.MULTIPART_FORM_DATA, "test.png"); // generate multipart byte stream and add to payload of post package HttpEntity multipart = builder.build(); ByteArrayOutputStream multipartOutStream = new ByteArrayOutputStream( (int) multipart.getContentLength()); multipart.writeTo(multipartOutStream); request.addPayload(multipartOutStream.toByteArray()); // set header of post package Header contentType = multipart.getContentType(); request.addHeader(contentType.getName(), contentType.getValue()); // send and response answer Response response = request.send(); return response.getBody(); } else { throw new RuntimeException("message and image needed"); } }
From source file:com.sat.vcse.automation.utils.http.HttpClient.java
/** * create HttpEntity for multi part file upload * @param file : file to upload, must be in class path * @param contentType/*from ww w. j a va2s . c o m*/ * @return HttpEntity * @throws FileNotFoundException */ private HttpEntity getMultiPartEntity(final File file, String formName) throws FileNotFoundException { InputStream is = null; if (file.exists()) { is = new FileInputStream(file); } else { LogHandler.warn("File not found, so trying to read it from class path now"); is = HttpClient.class.getResourceAsStream(file.getPath()); } if (null == formName) { formName = file.getName(); } final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addBinaryBody(formName, is, ContentType.MULTIPART_FORM_DATA, file.getName()); return builder.build(); }
From source file:com.intuit.tank.httpclient4.TankHttpClient4.java
private HttpEntity buildParts(BaseRequest request) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (PartHolder h : TankHttpUtil.getPartsFromBody(request)) { if (h.getFileName() == null) { if (h.isContentTypeSet()) { builder.addTextBody(h.getPartName(), new String(h.getBodyAsString()), ContentType.create(h.getContentType())); } else { builder.addTextBody(h.getPartName(), new String(h.getBodyAsString())); }/*ww w .ja va2s . com*/ } else { if (h.isContentTypeSet()) { builder.addBinaryBody(h.getPartName(), h.getBody(), ContentType.create(h.getContentType()), h.getFileName()); } else { builder.addBinaryBody(h.getFileName(), h.getBody()); } } } return builder.build(); }