List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder addPart
public MultipartEntityBuilder addPart(final String name, final ContentBody contentBody)
From source file:com.autonomy.aci.client.transport.AciParameter.java
@Override public void addToEntity(final MultipartEntityBuilder builder, final Charset charset) { builder.addPart(name, new StringBody(value, ContentType.create("text/plain", charset))); }
From source file:com.cloudera.livy.client.http.LivyConnection.java
synchronized <V> V post(File f, Class<V> retType, String paramName, String uri, Object... uriParams) throws Exception { HttpPost post = new HttpPost(); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart(paramName, new FileBody(f)); post.setEntity(builder.build());/*w w w. j av a 2s .c o m*/ return sendRequest(post, retType, uri, uriParams); }
From source file:io.undertow.servlet.test.security.basic.ServletCertAndDigestAuthTestCase.java
@Test public void testMultipartRequest() throws Exception { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 2000; i++) { sb.append("0123456789"); }//from w w w. ja v a 2 s . com try (TestHttpClient client = new TestHttpClient()) { // create POST request MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("part1", new ByteArrayBody(sb.toString().getBytes(), "file.txt")); builder.addPart("part2", new StringBody("0123456789", ContentType.TEXT_HTML)); HttpEntity entity = builder.build(); client.setSSLContext(clientSSLContext); String url = DefaultServer.getDefaultServerSSLAddress() + BASE_PATH + "multipart"; HttpPost post = new HttpPost(url); post.setEntity(entity); post.addHeader(AUTHORIZATION.toString(), BASIC + " " + FlexBase64 .encodeString(("user1" + ":" + "password1").getBytes(StandardCharsets.UTF_8), false)); HttpResponse result = client.execute(post); assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); } }
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 {/* w w w .ja v a 2s.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: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/*from w w w. jav a 2 s .c o 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: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); HttpEntity entity = builder.build(); post.setEntity(entity);/*w ww . j a va 2 s . c o m*/ 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.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 . ja va 2 s . c o 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:it.polimi.diceH2020.plugin.net.NetworkManager.java
/** * Sends to the backend the models to be simulated * /*from ww w.j a va 2 s.co m*/ * @param files * The model files * @param scenario * The scenario parameter * @throws UnsupportedEncodingException */ public void sendModel(List<File> files, String scenario) throws UnsupportedEncodingException { HttpClient httpclient = HttpClients.createDefault(); HttpResponse response; HttpPost post = new HttpPost(uploadRest); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("scenario", new StringBody(scenario, ContentType.DEFAULT_TEXT)); for (File file : files) { builder.addPart("file[]", new FileBody(file)); } post.setEntity(builder.build()); try { response = httpclient.execute(post); String json = EntityUtils.toString(response.getEntity()); HttpPost repost = new HttpPost(this.getLink(json)); response = httpclient.execute(repost); String js = EntityUtils.toString(response.getEntity()); parseJson(js); System.out.println("Code : " + response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != 200) { System.err.println("Error: POST not succesfull"); } else { } System.out.println(Configuration.getCurrent().getID()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:jog.my.memory.gcm.ServerUtilities.java
/** * Uploads a file to the server./*from w w w . jav a2 s . c o m*/ * @param context - Context of the app where the file is * @param serverUrl - URL of the server * @param uri - URI of the file * @return - response of posting the file to server */ public static String postFile(Context context, String serverUrl, Uri uri) { //TODO: Get the location sent up in here too! HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(serverUrl + "/upload"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // //Create the FileBody // final File file = new File(uri.getPath()); // FileBody fb = new FileBody(file); // deal with the file ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Bitmap bitmap = BitmapFactory.decodeFile(getRealPathFromURI(uri, context)); bitmap.compress(Bitmap.CompressFormat.JPEG, 75, byteArrayOutputStream); byte[] byteData = byteArrayOutputStream.toByteArray(); //String strData = Base64.encodeToString(data, Base64.DEFAULT); // I have no idea why Im doing this ByteArrayBody byteArrayBody = new ByteArrayBody(byteData, "image"); // second parameter is the name of the image (//TODO HOW DO I MAKE IT USE THE IMAGE FILENAME?) builder.addPart("myFile", byteArrayBody); builder.addTextBody("foo", "test text"); HttpEntity entity = builder.build(); post.setEntity(entity); try { HttpResponse response = client.execute(post); Log.d(TAG, "The response code was: " + response.getStatusLine().getStatusCode()); } catch (Exception e) { Log.d(TAG, "The image was not successfully uploaded."); } return null; // HttpClient httpclient = new DefaultHttpClient(); // HttpPost httppost = new HttpPost(serverUrl+"/postFile.do"); // // InputStream stream = null; // try { // stream = context.getContentResolver().openInputStream(uri); // // InputStreamEntity reqEntity = new InputStreamEntity(stream, -1); // // httppost.setEntity(reqEntity); // // HttpResponse response = httpclient.execute(httppost); // Log.d(TAG,"The response code was: "+response.getStatusLine().getStatusCode()); // if (response.getStatusLine().getStatusCode() == 200) { // // file uploaded successfully! // } else { // throw new RuntimeException("server couldn't handle request"); // } // return response.toString(); // } catch (Exception e) { // e.printStackTrace(); // // // handle error // } finally { // try { // stream.close(); // }catch(IOException ioe){ // ioe.printStackTrace(); // } // } // return null; }
From source file:apimanager.ZohoReportsAPIManager.java
public boolean postBulkJSONImport(JSONObject urlParams, JSONObject postParams) throws IOException { //CloseableHttpClient httpclient = HttpClients.createDefault(); loggerObj.log(Level.INFO, "Inisde postBulkJSONImport"); JSONObject httpPostObjectParams = new JSONObject(); String emailaddr = (String) urlParams.get("URLEmail"); String dbName = (String) urlParams.get("DBName"); String tableName = (String) urlParams.get("TableName"); String authToken = (String) urlParams.get(AUTHTOKEN); String url = "https://reportsapi.zoho.com/api/" + emailaddr + "/" + URLEncoder.encode(dbName, "UTF-8") + "/" + URLEncoder.encode(tableName, "UTF-8") + "?ZOHO_ACTION=IMPORT&ZOHO_OUTPUT_FORMAT=json&ZOHO_ERROR_FORMAT=json&authtoken=" + authToken + "&ZOHO_API_VERSION=1.0"; loggerObj.log(Level.INFO, "url params are:" + url); httpPostObjectParams.put("url", url); String jsonFileName = (String) postParams.get("jsonFileName"); FileBody jsonFile = new FileBody(new File(jsonFileName)); String ZOHO_IMPORT_FILETYPE = (String) postParams.get("ZOHO_IMPORT_FILETYPE"); String ZOHO_IMPORT_TYPE = (String) postParams.get("ZOHO_IMPORT_TYPE"); String ZOHO_AUTO_IDENTIFY = (String) postParams.get("ZOHO_AUTO_IDENTIFY"); String ZOHO_CREATE_TABLE = (String) postParams.get("ZOHO_CREATE_TABLE"); String ZOHO_ON_IMPORT_ERROR = (String) postParams.get("ZOHO_ON_IMPORT_ERROR"); String ZOHO_MATCHING_COLUMNS = (String) postParams.get("ZOHO_MATCHING_COLUMNS"); String ZOHO_DATE_FORMAT = (String) postParams.get("ZOHO_DATE_FORMAT"); String ZOHO_SELECTED_COLUMNS = (String) postParams.get("ZOHO_SELECTED_COLUMNS"); loggerObj.log(Level.INFO, "httpPost params are:" + postParams.toJSONString()); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("ZOHO_FILE", jsonFile); builder.addTextBody("ZOHO_IMPORT_FILETYPE", ZOHO_IMPORT_FILETYPE); builder.addTextBody("ZOHO_IMPORT_TYPE", ZOHO_IMPORT_TYPE); builder.addTextBody("ZOHO_AUTO_IDENTIFY", ZOHO_AUTO_IDENTIFY); builder.addTextBody("ZOHO_CREATE_TABLE", ZOHO_CREATE_TABLE); builder.addTextBody("ZOHO_ON_IMPORT_ERROR", ZOHO_ON_IMPORT_ERROR); if (ZOHO_MATCHING_COLUMNS != null) { builder.addTextBody("ZOHO_MATCHING_COLUMNS", ZOHO_MATCHING_COLUMNS); }/*w ww .j av a 2 s . c o m*/ if (ZOHO_SELECTED_COLUMNS != null) { builder.addTextBody("ZOHO_SELECTED_COLUMNS", ZOHO_SELECTED_COLUMNS); } builder.addTextBody("ZOHO_DATE_FORMAT", ZOHO_DATE_FORMAT); httpPostObjectParams.put("multiPartEntityBuilder", builder); HttpsClient httpsClientObj = new HttpsClient(); boolean isSuccessfulPost = httpsClientObj.httpsPost(url, builder, null); return isSuccessfulPost; }