List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder build
public HttpEntity build()
From source file:connection.ChaperOnConnection.java
private HttpPost GetPostHTTP(String email, String password, String firstname, String username, String imagePath, String street, String apartment, String city, String postal, String country, String lastname, String description, int rideType, double lattitude, double longitude, String phone, int availableseats, String licenseImage) {//from w w w. j a v a2s .c o m Bitmap bitmap = BitmapFactory.decodeFile(imagePath); Bitmap bitmap2 = BitmapFactory.decodeFile(licenseImage); HttpPost request = new HttpPost(REGISTER_URL); String param = "{\"phone\":\"" + phone + "\",\"email\":\"" + email + "\",\"password\": \"" + password + "\",\"username\": \"" + username + "\",\"availableSeats\":" + availableseats + ",\"type\": " + rideType + ",\"lattitude\": " + lattitude + ",\"longtitude\": " + longitude + ",\"street\": \"" + street + "\",\"appartment\": \"" + apartment + "\",\"city\": \"" + city + "\",\"zip\": \"" + postal + "\",\"country\": \"" + country + "\",\"lname\": \"" + lastname + "\",\"description\": \"" + description + "\",\"fname\": \"" + firstname + "\"}"; String BOUNDARY = "---------------------------41184676334"; request.setHeader("enctype", "multipart/form-data; boundary=" + BOUNDARY); request.setHeader("app-id", "appid"); request.setHeader("app-key", "appkey"); MultipartEntityBuilder entity = MultipartEntityBuilder.create(); try { entity.addPart("data", new StringBody(param)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos2 = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 70, bos); bitmap2.compress(Bitmap.CompressFormat.JPEG, 70, bos2); InputStream in = new ByteArrayInputStream(bos.toByteArray()); InputStream in2 = new ByteArrayInputStream(bos2.toByteArray()); ContentBody image = new InputStreamBody(in, "image/jpeg"); ContentBody image2 = new InputStreamBody(in2, "image/jpeg"); entity.addPart("image", image); entity.addPart("licenceimage", image2); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } request.setEntity(entity.build()); return request; }
From source file:org.wso2.msf4j.HttpServerTest.java
@Test public void tesFormParamWithCollection() throws IOException { // Send x-form-url-encoded request HttpURLConnection connection = request("/test/v1/formParamWithList", HttpMethod.POST); String rawData = "names=WSO2&names=IBM"; ByteBuffer encodedData = Charset.defaultCharset().encode(rawData); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED); connection.setRequestProperty("Content-Length", String.valueOf(encodedData.array().length)); try (OutputStream os = connection.getOutputStream()) { os.write(Arrays.copyOf(encodedData.array(), encodedData.limit())); }//from w w w . j a v a 2 s .c om InputStream inputStream = connection.getInputStream(); String response = StreamUtil.asString(inputStream); IOUtils.closeQuietly(inputStream); connection.disconnect(); assertEquals(response, "2"); // Send multipart/form-data request connection = request("/test/v1/formParamWithList", HttpMethod.POST); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("names", new StringBody("WSO2", ContentType.TEXT_PLAIN)); builder.addPart("names", new StringBody("IBM", ContentType.TEXT_PLAIN)); builder.addPart("names", new StringBody("Oracle", ContentType.TEXT_PLAIN)); HttpEntity build = builder.build(); connection.setRequestProperty("Content-Type", build.getContentType().getValue()); try (OutputStream out = connection.getOutputStream()) { build.writeTo(out); } inputStream = connection.getInputStream(); response = StreamUtil.asString(inputStream); IOUtils.closeQuietly(inputStream); connection.disconnect(); assertEquals(response, "3"); // Send x-form-url-encoded request connection = request("/test/v1/formParamWithSet", HttpMethod.POST); rawData = "names=WSO2&names=IBM&names=IBM"; encodedData = Charset.defaultCharset().encode(rawData); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED); connection.setRequestProperty("Content-Length", String.valueOf(encodedData.array().length)); try (OutputStream os = connection.getOutputStream()) { os.write(Arrays.copyOf(encodedData.array(), encodedData.limit())); } inputStream = connection.getInputStream(); response = StreamUtil.asString(inputStream); IOUtils.closeQuietly(inputStream); connection.disconnect(); assertEquals(response, "2"); // Send multipart/form-data request connection = request("/test/v1/formParamWithSet", HttpMethod.POST); builder = MultipartEntityBuilder.create(); builder.addPart("names", new StringBody("WSO2", ContentType.TEXT_PLAIN)); builder.addPart("names", new StringBody("IBM", ContentType.TEXT_PLAIN)); builder.addPart("names", new StringBody("IBM", ContentType.TEXT_PLAIN)); builder.addPart("names", new StringBody("Oracle", ContentType.TEXT_PLAIN)); build = builder.build(); connection.setRequestProperty("Content-Type", build.getContentType().getValue()); try (OutputStream out = connection.getOutputStream()) { build.writeTo(out); } inputStream = connection.getInputStream(); response = StreamUtil.asString(inputStream); IOUtils.closeQuietly(inputStream); connection.disconnect(); assertEquals(response, "3"); }
From source file:org.andstatus.app.net.http.HttpConnectionApacheCommon.java
private void fillMultiPartPost(HttpPost postMethod, JSONObject formParams) throws ConnectionException { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); Uri mediaUri = null;/*from ww w . j a v a 2s . c o m*/ String mediaPartName = ""; Iterator<String> iterator = formParams.keys(); ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8); while (iterator.hasNext()) { String name = iterator.next(); String value = formParams.optString(name); if (HttpConnection.KEY_MEDIA_PART_NAME.equals(name)) { mediaPartName = value; } else if (HttpConnection.KEY_MEDIA_PART_URI.equals(name)) { mediaUri = UriUtils.fromString(value); } else { // see http://stackoverflow.com/questions/19292169/multipartentitybuilder-and-charset builder.addTextBody(name, value, contentType); } } if (!TextUtils.isEmpty(mediaPartName) && !UriUtils.isEmpty(mediaUri)) { try { InputStream ins = MyContextHolder.get().context().getContentResolver().openInputStream(mediaUri); ContentType contentType2 = ContentType.create(MyContentType.uri2MimeType(mediaUri, null)); builder.addBinaryBody(mediaPartName, ins, contentType2, mediaUri.getPath()); } catch (SecurityException e) { throw new ConnectionException("mediaUri='" + mediaUri + "'", e); } catch (FileNotFoundException e) { throw new ConnectionException("mediaUri='" + mediaUri + "'", e); } } postMethod.setEntity(builder.build()); }
From source file:sx.blah.discord.handle.impl.obj.Channel.java
@Override public IMessage sendFiles(String content, boolean tts, EmbedObject embed, AttachmentPartEntry... entries) { PermissionUtils.requirePermissions(this, client.getOurUser(), Permissions.SEND_MESSAGES, Permissions.ATTACH_FILES); try {//from ww w .j a va2 s . c o m MultipartEntityBuilder builder = MultipartEntityBuilder.create(); if (entries.length == 1) { builder.addBinaryBody("file", entries[0].getFileData(), ContentType.APPLICATION_OCTET_STREAM, entries[0].getFileName()); } else { for (int i = 0; i < entries.length; i++) { builder.addBinaryBody("file" + i, entries[i].getFileData(), ContentType.APPLICATION_OCTET_STREAM, entries[i].getFileName()); } } builder.addTextBody("payload_json", DiscordUtils.MAPPER_NO_NULLS.writeValueAsString(new FilePayloadObject(content, tts, embed)), ContentType.MULTIPART_FORM_DATA.withCharset("UTF-8")); HttpEntity fileEntity = builder.build(); MessageObject messageObject = DiscordUtils.MAPPER .readValue( client.REQUESTS.POST.makeRequest(DiscordEndpoints.CHANNELS + id + "/messages", fileEntity, new BasicNameValuePair("Content-Type", "multipart/form-data")), MessageObject.class); return DiscordUtils.getMessageFromJSON(this, messageObject); } catch (IOException e) { throw new DiscordException("JSON Parsing exception!", e); } }
From source file:org.wso2.carbon.ml.integration.common.utils.MLHttpClient.java
/** * Upload a sample datatset from resources * // w ww . j a v a 2s . c o m * @param datasetName Name for the dataset * @param version Version for the dataset * @param tableName Relative path the CSV file in resources * @return Response from the backend * @throws MLHttpClientException */ public CloseableHttpResponse uploadDatasetFromDAS(String datasetName, String version, String tableName) throws MLHttpClientException { CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(getServerUrlHttps() + "/api/datasets/"); httpPost.setHeader(MLIntegrationTestConstants.AUTHORIZATION_HEADER, getBasicAuthKey()); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addPart("description", new StringBody("Sample dataset for Testing", ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("sourceType", new StringBody("das", ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("destination", new StringBody("file", ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("dataFormat", new StringBody("CSV", ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("sourcePath", new StringBody(tableName, ContentType.TEXT_PLAIN)); if (datasetName != null) { multipartEntityBuilder.addPart("datasetName", new StringBody(datasetName, ContentType.TEXT_PLAIN)); } if (version != null) { multipartEntityBuilder.addPart("version", new StringBody(version, ContentType.TEXT_PLAIN)); } multipartEntityBuilder.addBinaryBody("file", new byte[] {}, ContentType.APPLICATION_OCTET_STREAM, "IndiansDiabetes.csv"); httpPost.setEntity(multipartEntityBuilder.build()); return httpClient.execute(httpPost); } catch (Exception e) { throw new MLHttpClientException("Failed to upload dataset from DAS " + tableName, e); } }
From source file:com.serphacker.serposcope.scraper.http.ScrapClient.java
public int post(String url, Map<String, Object> data, PostType dataType, String charset, String referrer) { clearPreviousRequest();/* ww w . j a v a 2 s . c o m*/ HttpPost request = new HttpPost(url); HttpEntity entity = null; if (charset == null) { charset = "utf-8"; } Charset detectedCharset = null; try { detectedCharset = Charset.forName(charset); } catch (Exception ex) { LOG.warn("invalid charset name {}, switching to utf-8"); detectedCharset = Charset.forName("utf-8"); } data = handleUnsupportedEncoding(data, detectedCharset); switch (dataType) { case URL_ENCODED: List<NameValuePair> formparams = new ArrayList<>(); for (Map.Entry<String, Object> entry : data.entrySet()) { if (entry.getValue() instanceof String) { formparams.add(new BasicNameValuePair(entry.getKey(), (String) entry.getValue())); } else { LOG.warn("trying to url encode non string data"); formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString())); } } try { entity = new UrlEncodedFormEntity(formparams, detectedCharset); } catch (Exception ex) { statusCode = -1; exception = ex; return statusCode; } break; case MULTIPART: MultipartEntityBuilder builder = MultipartEntityBuilder.create().setCharset(detectedCharset) .setMode(HttpMultipartMode.BROWSER_COMPATIBLE); ContentType formDataCT = ContentType.create("form-data", detectedCharset); // formDataCT = ContentType.DEFAULT_TEXT; for (Map.Entry<String, Object> entry : data.entrySet()) { String key = entry.getKey(); if (entry.getValue() instanceof String) { builder = builder.addTextBody(key, (String) entry.getValue(), formDataCT); } else if (entry.getValue() instanceof byte[]) { builder = builder.addBinaryBody(key, (byte[]) entry.getValue()); } else if (entry.getValue() instanceof ContentBody) { builder = builder.addPart(key, (ContentBody) entry.getValue()); } else { exception = new UnsupportedOperationException( "unssuported body type " + entry.getValue().getClass()); return statusCode = -1; } } entity = builder.build(); break; default: exception = new UnsupportedOperationException("unspported PostType " + dataType); return statusCode = -1; } request.setEntity(entity); if (referrer != null) { request.addHeader("Referer", referrer); } return request(request); }
From source file:nl.uva.mediamosa.impl.MediaMosaImpl.java
/** * @param postRequest//from ww w .j ava2s . c o m * @param postParams * @return * @throws java.io.IOException */ public Response doPostRequest(String uploadHost, String postRequest, String postParams, InputStream stream, String mimeType, String filename) throws IOException { HttpPost httpPost = new HttpPost(uploadHost + postRequest); MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); mpBuilder.addBinaryBody("file", stream, ContentType.create(mimeType), filename); List<NameValuePair> nvps = URLEncodedUtils.parse(postParams, Charset.forName("UTF-8")); for (NameValuePair nameValuePair : nvps) { mpBuilder.addTextBody(nameValuePair.getName(), nameValuePair.getValue()); } httpPost.setEntity(mpBuilder.build()); return UnmarshallUtil.unmarshall(getXmlTransformedResponse(httpPost)); }
From source file:org.wso2.carbon.ml.integration.common.utils.MLHttpClient.java
/** * Upload a sample datatset from resources * /*from www .j a v a2 s.c o m*/ * @param datasetName Name for the dataset * @param version Version for the dataset * @param resourcePath Relative path the CSV file in resources * @return Response from the backend * @throws MLHttpClientException */ public CloseableHttpResponse uploadDatasetFromCSV(String datasetName, String version, String resourcePath) throws MLHttpClientException { CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(getServerUrlHttps() + "/api/datasets/"); httpPost.setHeader(MLIntegrationTestConstants.AUTHORIZATION_HEADER, getBasicAuthKey()); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addPart("description", new StringBody("Sample dataset for Testing", ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("sourceType", new StringBody("file", ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("destination", new StringBody("file", ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("dataFormat", new StringBody("CSV", ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("containsHeader", new StringBody("true", ContentType.TEXT_PLAIN)); if (datasetName != null) { multipartEntityBuilder.addPart("datasetName", new StringBody(datasetName, ContentType.TEXT_PLAIN)); } if (version != null) { multipartEntityBuilder.addPart("version", new StringBody(version, ContentType.TEXT_PLAIN)); } if (resourcePath != null) { File file = new File(getResourceAbsolutePath(resourcePath)); multipartEntityBuilder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, "IndiansDiabetes.csv"); } httpPost.setEntity(multipartEntityBuilder.build()); return httpClient.execute(httpPost); } catch (Exception e) { throw new MLHttpClientException("Failed to upload dataset from csv " + resourcePath, e); } }
From source file:com.lgallardo.youtorrentcontroller.JSONParser.java
public void postCommand(String command, String hash) throws JSONParserStatusCodeException { String key = "hash"; String urlContentType = "application/x-www-form-urlencoded"; String boundary = null;//from ww w.jav a 2 s . c o m StringBuilder fileContent = null; HttpResponse httpResponse; DefaultHttpClient httpclient; String url = ""; // Log.d("Debug", "JSONParser - command: " + command); if ("start".equals(command) || "startSelected".equals(command)) { url = url + "gui/?action=start&hash=" + hash; } if ("pause".equals(command) || "pauseSelected".equals(command)) { url = url + "gui/?action=pause&hash=" + hash; } if ("stop".equals(command) || "stopSelected".equals(command)) { url = url + "gui/?action=stop&hash=" + hash; Log.d("Debug", "Stoping torrent " + hash); } if ("delete".equals(command) || "deleteSelected".equals(command)) { url = url + "gui/?action=remove&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("deleteDrive".equals(command) || "deleteDriveSelected".equals(command)) { url = url + "gui/?action=removedata&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("addTorrent".equals(command)) { URI hash_uri = null; try { hash_uri = new URI(hash); hash = hash_uri.toString(); // Log.d("Debug","Torrent URL: "+ hash); } catch (URISyntaxException e) { Log.e("Debug", "URISyntaxException: " + e.toString()); } url = url + "gui/?action=add-url&s=" + hash; // key = "urls"; } if ("addTorrentFile".equals(command)) { url = url + "gui/?action=add-file"; key = "urls"; boundary = "-----------------------" + (new Date()).getTime(); urlContentType = "multipart/form-data; boundary=" + boundary; // urlContentType = "multipart/form-data"; } // if ("pauseall".equals(command)) { // url = "command/pauseall"; // } // // if ("pauseAll".equals(command)) { // url = "command/pauseAll"; // } // // // if ("resumeall".equals(command)) { // url = "command/resumeall"; // } // // if ("resumeAll".equals(command)) { // url = "command/resumeAll"; // } if ("increasePrio".equals(command)) { url = url + "gui/?action=queueup&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("decreasePrio".equals(command)) { url = url + "gui/?action=queuedown&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("maxPrio".equals(command)) { url = url + "gui/?action=queuetop&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("minPrio".equals(command)) { url = url + "gui/?action=queuebottom&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("setQBittorrentPrefefrences".equals(command)) { url = "command/setPreferences"; key = "json"; } if ("recheckSelected".equals(command)) { url = url + "gui/?action=recheck&hash=" + hash.replace("|", "&hash="); } // if ("toggleFirstLastPiecePrio".equals(command)) { // url = "command/toggleFirstLastPiecePrio"; // key = "hashes"; // // } // // if ("toggleSequentialDownload".equals(command)) { // url = "command/toggleSequentialDownload"; // key = "hashes"; // // } // if server is publish in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; } HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = connection_timeout * 1000; // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = data_timeout * 1000; // Set http parameters HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpProtocolParams.setUserAgent(httpParameters, "youTorrent Controller"); HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); // Making HTTP request HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol); // httpclient = new DefaultHttpClient(); httpclient = getNewHttpClient(); // Set http parameters httpclient.setParams(httpParameters); try { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); httpclient.getCredentialsProvider().setCredentials(authScope, credentials); url = protocol + "://" + hostname + ":" + port + "/" + url + "&token=" + token; // Log.d("Debug", "JSONParser - url: " + url); HttpPost httpget = new HttpPost(url); if ("addTorrent".equals(command)) { URI hash_uri = new URI(hash); hash = hash_uri.toString(); } // In order to pass the has we must set the pair name value BasicNameValuePair bnvp = new BasicNameValuePair(key, hash); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(bnvp); httpget.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); // Set content type and urls if ("increasePrio".equals(command) || "decreasePrio".equals(command) || "maxPrio".equals(command)) { httpget.setHeader("Content-Type", urlContentType); } // Set cookie if (this.cookie != null) { httpget.setHeader("Cookie", this.cookie); } // Set content type and urls if ("addTorrentFile".equals(command)) { // Log.d("Debug", "JSONParser - urlContentType: " + urlContentType); // Log.d("Debug", "JSONParser - hash: " + Uri.decode(URLEncoder.encode(hash, "UTF-8"))); // Log.d("Debug", "JSONParser - hash: " + hash); httpget.setHeader("Content-Type", urlContentType); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // Add boundary builder.setBoundary(boundary); // Add torrent file as binary File file = new File(hash); // FileBody fileBody = new FileBody(file); // builder.addPart("file", fileBody); builder.addBinaryBody("torrent_file", file, ContentType.DEFAULT_BINARY, null); // builder.addBinaryBody("upfile", file, ContentType.create(urlContentType), hash); // Build entity HttpEntity entity = builder.build(); // Set entity to http post httpget.setEntity(entity); } httpResponse = httpclient.execute(targetHost, httpget); StatusLine statusLine = httpResponse.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); if (mStatusCode != 200) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(mStatusCode); } HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { } catch (ClientProtocolException e) { Log.e("Debug", "Client: " + e.toString()); e.printStackTrace(); } catch (IOException e) { Log.e("Debug", "IO: " + e.toString()); // e.printStackTrace(); httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(TIMEOUT_ERROR); } catch (JSONParserStatusCodeException e) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(e.getCode()); } catch (Exception e) { Log.e("Debug", "Generic: " + e.toString()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }