List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder addTextBody
public MultipartEntityBuilder addTextBody(final String name, final String text, final ContentType contentType)
From source file:com.adobe.aem.demo.communities.Loader.java
private static String doThumbnail(String hostname, String port, String adminPassword, String csvfile, String filename) {/* ww w. ja v a 2 s.com*/ 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:org.andstatus.app.net.http.HttpConnectionApacheCommon.java
private void fillMultiPartPost(HttpPost postMethod, JSONObject formParams) throws ConnectionException { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); Uri mediaUri = null;//from w w w . j a va 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:com.qmetry.qaf.automation.integration.qmetry.qmetry6.QMetryRestWebservice.java
/** * attach log using run id//from ww w. jav a 2 s. c o m * * @param token * - token generate using username and password * @param scope * : project:release:cycle * @param testCaseRunId * @param filePath * - absolute path of file to be attached * @return */ public int attachTestLogsUsingRunId(long testCaseRunId, File filePath) { try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss"); final String CurrentDate = format.format(new Date()); Path path = Paths.get(filePath.toURI()); byte[] outFileArray = Files.readAllBytes(path); if (outFileArray != null) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(serviceUrl + "/rest/attachments/testLog"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody bin = new FileBody(filePath); builder.addTextBody("desc", "Attached on " + CurrentDate, org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addTextBody("type", "TCR", org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addTextBody("entityId", String.valueOf(testCaseRunId), org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addPart("file", bin); HttpEntity reqEntity = builder.build(); httppost.setEntity(reqEntity); httppost.addHeader("usertoken", token); httppost.addHeader("scope", scope); CloseableHttpResponse response = httpclient.execute(httppost); String str = null; try { str = EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); } finally { } JsonElement gson = new Gson().fromJson(str, JsonElement.class); JsonElement data = gson.getAsJsonObject().get("data"); int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString()); return id; } finally { httpclient.close(); } } else { System.out.println(filePath + " file does not exists"); } } catch (Exception ex) { System.out.println("Error in attaching file - " + filePath); System.out.println(ex.getMessage()); } return 0; }
From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.QMetryRestWebservice.java
/** * attach log using run id//from w w w. ja va 2 s . c o m * * @param token * - token generate using username and password * @param scope * : project:release:cycle * @param testCaseRunId * @param filePath * - absolute path of file to be attached * @param serviceUrl * @param scope * @return */ public int attachTestLogsUsingRunID(String serviceUrl, long testCaseRunId, File filePath, String scope) { try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss"); final String CurrentDate = format.format(new Date()); Path path = Paths.get(filePath.toURI()); byte[] outFileArray = Files.readAllBytes(path); if (outFileArray != null) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(serviceUrl + "/rest/attachments/testLog"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody bin = new FileBody(filePath); builder.addTextBody("desc", "Attached on " + CurrentDate, org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addTextBody("type", "TCR", org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addTextBody("entityId", String.valueOf(testCaseRunId), org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addPart("file", bin); HttpEntity reqEntity = builder.build(); httppost.setEntity(reqEntity); httppost.addHeader("usertoken", token); httppost.addHeader("scope", scope); CloseableHttpResponse response = httpclient.execute(httppost); String str = null; try { str = EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); } finally { } JsonElement gson = new Gson().fromJson(str, JsonElement.class); JsonElement data = gson.getAsJsonObject().get("data"); int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString()); return id; } finally { httpclient.close(); } } else { System.out.println(filePath + " file does not exists"); } } catch (Exception ex) { System.out.println("Error in attaching file - " + filePath); System.out.println(ex.getMessage()); } return 0; }
From source file:com.smartsheet.api.internal.AbstractResources.java
/** * Create a multipart upload request./*w w w. j a v a 2 s . c o m*/ * * @param url the url * @param t the object to create * @param partName the name of the part * @param inputstream the file inputstream * @param contentType the type of the file to be attached * @return the http request * @throws UnsupportedEncodingException the unsupported encoding exception */ public <T> Attachment attachFile(String url, T t, String partName, InputStream inputstream, String contentType, String attachmentName) throws SmartsheetException { Util.throwIfNull(inputstream, contentType); Attachment attachment = null; final String boundary = "----" + System.currentTimeMillis(); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost uploadFile = createHttpPost(this.getSmartsheet().getBaseURI().resolve(url)); try { uploadFile.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary); } catch (Exception e) { throw new RuntimeException(e); } MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setBoundary(boundary); builder.addTextBody(partName, this.getSmartsheet().getJsonSerializer().serialize(t), ContentType.APPLICATION_JSON); builder.addBinaryBody("file", inputstream, ContentType.create(contentType), attachmentName); org.apache.http.HttpEntity multipart = builder.build(); uploadFile.setEntity(multipart); try { CloseableHttpResponse response = httpClient.execute(uploadFile); org.apache.http.HttpEntity responseEntity = response.getEntity(); attachment = this.getSmartsheet().getJsonSerializer() .deserializeResult(Attachment.class, responseEntity.getContent()).getResult(); } catch (Exception e) { throw new RuntimeException(e); } return attachment; }
From source file:com.smartsheet.api.internal.AbstractResources.java
/** * Create a resource using Smartsheet REST API. * * Exceptions://ww w .ja v a 2s. c o m * IllegalArgumentException : if any argument is null, or path is empty string * InvalidRequestException : if there is any problem with the REST API request * AuthorizationException : if there is any problem with the REST API authorization(access token) * ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting) * SmartsheetRestException : if there is any other REST API related error occurred during the operation * SmartsheetException : if there is any other error occurred during the operation * * @param <T> the generic type * @param path the relative path of the resource collections * @param objectClass the resource object class * @param object the object to create * @return the created resource * @throws SmartsheetException the smartsheet exception */ protected <T> T createResourceWithAttachment(String path, Class<T> objectClass, T object, String partName, InputStream inputStream, String contentType, String attachmentName) throws SmartsheetException { Util.throwIfNull(path, object); Util.throwIfEmpty(path); HttpRequest request; final String boundary = "----" + System.currentTimeMillis(); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost uploadFile = createHttpPost(this.getSmartsheet().getBaseURI().resolve(path)); try { uploadFile.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary); } catch (Exception e) { throw new RuntimeException(e); } MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setBoundary(boundary); builder.addTextBody(partName, this.getSmartsheet().getJsonSerializer().serialize(object), ContentType.APPLICATION_JSON); builder.addBinaryBody("file", inputStream, ContentType.create(contentType), attachmentName); org.apache.http.HttpEntity multipart = builder.build(); uploadFile.setEntity(multipart); T obj = null; //implement switch case try { CloseableHttpResponse response = httpClient.execute(uploadFile); org.apache.http.HttpEntity responseEntity = response.getEntity(); obj = this.getSmartsheet().getJsonSerializer() .deserializeResult(objectClass, responseEntity.getContent()).getResult(); } catch (Exception e) { throw new RuntimeException(e); } return obj; }
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();/*www .j a v a 2s .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: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.//from ww w . ja v a 2s. 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.gargoylesoftware.htmlunit.HttpWebConnection.java
/** * Creates an <tt>HttpMethod</tt> instance according to the specified parameters. * @param webRequest the request// w w w . j a v a 2s .co m * @param httpClientBuilder the httpClientBuilder that will be configured * @return the <tt>HttpMethod</tt> instance constructed according to the specified parameters * @throws IOException * @throws URISyntaxException */ @SuppressWarnings("deprecation") private HttpUriRequest makeHttpMethod(final WebRequest webRequest, final HttpClientBuilder httpClientBuilder) throws IOException, URISyntaxException { final String charset = webRequest.getCharset(); // Make sure that the URL is fully encoded. IE actually sends some Unicode chars in request // URLs; because of this we allow some Unicode chars in URLs. However, at this point we're // handing things over the HttpClient, and HttpClient will blow up if we leave these Unicode // chars in the URL. final URL url = UrlUtils.encodeUrl(webRequest.getUrl(), false, charset); // URIUtils.createURI is deprecated but as of httpclient-4.2.1, URIBuilder doesn't work here as it encodes path // what shouldn't happen here URI uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), url.getPath(), escapeQuery(url.getQuery()), null); if (getVirtualHost() != null) { uri = URI.create(getVirtualHost()); } final HttpRequestBase httpMethod = buildHttpMethod(webRequest.getHttpMethod(), uri); setProxy(httpMethod, webRequest); if (!(httpMethod instanceof HttpEntityEnclosingRequest)) { // this is the case for GET as well as TRACE, DELETE, OPTIONS and HEAD if (!webRequest.getRequestParameters().isEmpty()) { final List<NameValuePair> pairs = webRequest.getRequestParameters(); final org.apache.http.NameValuePair[] httpClientPairs = NameValuePair.toHttpClient(pairs); final String query = URLEncodedUtils.format(Arrays.asList(httpClientPairs), charset); uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), url.getPath(), query, null); httpMethod.setURI(uri); } } else { // POST as well as PUT and PATCH final HttpEntityEnclosingRequest method = (HttpEntityEnclosingRequest) httpMethod; if (webRequest.getEncodingType() == FormEncodingType.URL_ENCODED && method instanceof HttpPost) { final HttpPost postMethod = (HttpPost) method; if (webRequest.getRequestBody() == null) { final List<NameValuePair> pairs = webRequest.getRequestParameters(); final org.apache.http.NameValuePair[] httpClientPairs = NameValuePair.toHttpClient(pairs); final String query = URLEncodedUtils.format(Arrays.asList(httpClientPairs), charset); final StringEntity urlEncodedEntity = new StringEntity(query, charset); urlEncodedEntity.setContentType(URLEncodedUtils.CONTENT_TYPE); postMethod.setEntity(urlEncodedEntity); } else { final String body = StringUtils.defaultString(webRequest.getRequestBody()); final StringEntity urlEncodedEntity = new StringEntity(body, charset); urlEncodedEntity.setContentType(URLEncodedUtils.CONTENT_TYPE); postMethod.setEntity(urlEncodedEntity); } } else if (FormEncodingType.MULTIPART == webRequest.getEncodingType()) { final Charset c = getCharset(charset, webRequest.getRequestParameters()); final MultipartEntityBuilder builder = MultipartEntityBuilder.create().setLaxMode(); builder.setCharset(c); for (final NameValuePair pair : webRequest.getRequestParameters()) { if (pair instanceof KeyDataPair) { buildFilePart((KeyDataPair) pair, builder); } else { builder.addTextBody(pair.getName(), pair.getValue(), ContentType.create("text/plain", charset)); } } method.setEntity(builder.build()); } else { // for instance a PUT or PATCH request final String body = webRequest.getRequestBody(); if (body != null) { method.setEntity(new StringEntity(body, charset)); } } } configureHttpProcessorBuilder(httpClientBuilder, webRequest); // Tell the client where to get its credentials from // (it may have changed on the webClient since last call to getHttpClientFor(...)) final CredentialsProvider credentialsProvider = webClient_.getCredentialsProvider(); // if the used url contains credentials, we have to add this final Credentials requestUrlCredentials = webRequest.getUrlCredentials(); if (null != requestUrlCredentials && webClient_.getBrowserVersion().hasFeature(URL_AUTH_CREDENTIALS)) { final URL requestUrl = webRequest.getUrl(); final AuthScope authScope = new AuthScope(requestUrl.getHost(), requestUrl.getPort()); // updating our client to keep the credentials for the next request credentialsProvider.setCredentials(authScope, requestUrlCredentials); httpContext_.removeAttribute(HttpClientContext.TARGET_AUTH_STATE); } // if someone has set credentials to this request, we have to add this final Credentials requestCredentials = webRequest.getCredentials(); if (null != requestCredentials) { final URL requestUrl = webRequest.getUrl(); final AuthScope authScope = new AuthScope(requestUrl.getHost(), requestUrl.getPort()); // updating our client to keep the credentials for the next request credentialsProvider.setCredentials(authScope, requestCredentials); httpContext_.removeAttribute(HttpClientContext.TARGET_AUTH_STATE); } httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); httpContext_.removeAttribute(HttpClientContext.CREDS_PROVIDER); return httpMethod; }
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 {/*w w w .ja va 2 s . co 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); } }