List of usage examples for org.apache.http.entity ContentType MULTIPART_FORM_DATA
ContentType MULTIPART_FORM_DATA
To view the source code for org.apache.http.entity ContentType MULTIPART_FORM_DATA.
Click Source Link
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 ww . j av a 2 s .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.uploader.Vimeo.java
private VimeoResponse apiRequest(String endpoint, String methodName, Map<String, String> params, File file) throws IOException { // try(CloseableHttpClient client = HttpClientBuilder.create().build()) { CloseableHttpClient client = HttpClientBuilder.create().build(); // CloseableHttpClient client = HttpClients.createDefault(); System.out.println("Building HTTP Client"); // try {/*from w w w . ja v a 2 s . c o m*/ // client = // } catch(Exception e) { // System.out.println("Err in CloseableHttpClient"); // } // System.out.println(client); HttpRequestBase request = null; String url = null; if (endpoint.startsWith("http")) { url = endpoint; } else { url = new StringBuffer(VIMEO_SERVER).append(endpoint).toString(); } System.out.println(url); if (methodName.equals(HttpGet.METHOD_NAME)) { request = new HttpGet(url); } else if (methodName.equals(HttpPost.METHOD_NAME)) { request = new HttpPost(url); } else if (methodName.equals(HttpPut.METHOD_NAME)) { request = new HttpPut(url); } else if (methodName.equals(HttpDelete.METHOD_NAME)) { request = new HttpDelete(url); } else if (methodName.equals(HttpPatch.METHOD_NAME)) { request = new HttpPatch(url); } request.addHeader("Accept", "application/vnd.vimeo.*+json; version=3.2"); request.addHeader("Authorization", new StringBuffer(tokenType).append(" ").append(token).toString()); HttpEntity entity = null; if (params != null) { ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); for (String key : params.keySet()) { postParameters.add(new BasicNameValuePair(key, params.get(key))); } entity = new UrlEncodedFormEntity(postParameters); } else { if (file != null) { entity = new FileEntity(file, ContentType.MULTIPART_FORM_DATA); } } if (entity != null) { if (request instanceof HttpPost) { ((HttpPost) request).setEntity(entity); } else if (request instanceof HttpPatch) { ((HttpPatch) request).setEntity(entity); } else if (request instanceof HttpPut) { ((HttpPut) request).setEntity(entity); } } CloseableHttpResponse response = client.execute(request); String responseAsString = null; int statusCode = response.getStatusLine().getStatusCode(); if (methodName.equals(HttpPut.METHOD_NAME) || methodName.equals(HttpDelete.METHOD_NAME)) { JSONObject out = new JSONObject(); for (Header header : response.getAllHeaders()) { try { out.put(header.getName(), header.getValue()); } catch (Exception e) { System.out.println("Err in out.put"); } } responseAsString = out.toString(); } else if (statusCode != 204) { ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); responseAsString = out.toString("UTF-8"); out.close(); } JSONObject json = null; try { json = new JSONObject(responseAsString); } catch (Exception e) { json = new JSONObject(); } VimeoResponse vimeoResponse = new VimeoResponse(json, statusCode); response.close(); client.close(); return vimeoResponse; // } catch(IOException e) { // System.out.println("Error Building HTTP Client"); // } }
From source file:org.archive.modules.fetcher.FetchHTTPRequest.java
protected HttpEntity buildPostRequestEntity(CrawlURI curi) { String enctype = (String) curi.getData().get(CoreAttributeConstants.A_SUBMIT_ENCTYPE); if (enctype == null) { enctype = ContentType.APPLICATION_FORM_URLENCODED.getMimeType(); }//from w ww . ja v a2 s. co m @SuppressWarnings("unchecked") List<NameValue> submitData = (List<NameValue>) curi.getData().get(CoreAttributeConstants.A_SUBMIT_DATA); if (enctype.equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) { LinkedList<NameValuePair> nvps = new LinkedList<NameValuePair>(); for (NameValue nv : submitData) { nvps.add(new BasicNameValuePair(nv.name, nv.value)); } try { return new UrlEncodedFormEntity(nvps, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } else if (enctype.equals(ContentType.MULTIPART_FORM_DATA.getMimeType())) { MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (NameValue nv : submitData) { entityBuilder.addTextBody(escapeForMultipart(nv.name), escapeForMultipart(nv.value)); } return entityBuilder.build(); } else { throw new IllegalStateException("unsupported form submission enctype='" + enctype + "'"); } }
From source file:co.aurasphere.botmill.fb.internal.util.network.FbBotMillNetworkController.java
/** * POSTs a message as a JSON string to Facebook. * * @param recipient/*from w ww.j a v a 2 s.c o m*/ * the recipient * @param type * the type * @param file * the file */ public static void postFormDataMessage(String recipient, AttachmentType type, File file) { String pageToken = FbBotMillContext.getInstance().getPageToken(); // If the page token is invalid, returns. if (!validatePageToken(pageToken)) { return; } // TODO: add checks for valid attachmentTypes (FILE, AUDIO or VIDEO) HttpPost post = new HttpPost(FbBotMillNetworkConstants.FACEBOOK_BASE_URL + FbBotMillNetworkConstants.FACEBOOK_MESSAGES_URL + pageToken); FileBody filedata = new FileBody(file); StringBody recipientPart = new StringBody("{\"id\":\"" + recipient + "\"}", ContentType.MULTIPART_FORM_DATA); StringBody messagePart = new StringBody( "{\"attachment\":{\"type\":\"" + type.name().toLowerCase() + "\", \"payload\":{}}}", ContentType.MULTIPART_FORM_DATA); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.STRICT); builder.addPart("recipient", recipientPart); builder.addPart("message", messagePart); // builder.addPart("filedata", filedata); builder.addBinaryBody("filedata", file); builder.setContentType(ContentType.MULTIPART_FORM_DATA); // builder.setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW"); HttpEntity entity = builder.build(); post.setEntity(entity); // Logs the raw JSON for debug purposes. BufferedReader br; // post.addHeader("Content-Type", "multipart/form-data"); try { // br = new BufferedReader(new InputStreamReader( // ()))); Header[] allHeaders = post.getAllHeaders(); for (Header h : allHeaders) { logger.debug("Header {} -> {}", h.getName(), h.getValue()); } // String output = br.readLine(); } catch (Exception e) { e.printStackTrace(); } // postInternal(post); }
From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java
/** * This method is use to post data in multidata format * @param url// ww w. j av a 2 s .c o m * - backend url * @param mobileApplicationBean * - Bean class of the mobile application * @param headers * - header files */ public static String doPostMultiData(String url, MobileApplicationBean mobileApplicationBean, Map<String, String> headers) throws IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); // initializing headers if (headers != null && headers.size() > 0) { Iterator<String> itr = headers.keySet().iterator(); while (itr.hasNext()) { String key = itr.next(); httpPost.setHeader(key, headers.get(key)); } } MultipartEntityBuilder reqEntity; reqEntity = MultipartEntityBuilder.create(); reqEntity.addPart("version", new StringBody(mobileApplicationBean.getVersion(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("provider", new StringBody(mobileApplicationBean.getProvider(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("markettype", new StringBody(mobileApplicationBean.getMarkettype(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("platform", new StringBody(mobileApplicationBean.getPlatform(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("name", new StringBody(mobileApplicationBean.getName(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("description", new StringBody(mobileApplicationBean.getDescription(), ContentType.MULTIPART_FORM_DATA)); FileBody bannerImageFile = new FileBody(mobileApplicationBean.getBannerFilePath()); reqEntity.addPart("bannerFile", bannerImageFile); FileBody iconImageFile = new FileBody(mobileApplicationBean.getIconFile()); reqEntity.addPart("iconFile", iconImageFile); FileBody screenShot1 = new FileBody(mobileApplicationBean.getScreenShot1File()); reqEntity.addPart("screenshot1File", screenShot1); FileBody screenShot2 = new FileBody(mobileApplicationBean.getScreenShot2File()); reqEntity.addPart("screenshot2File", screenShot2); FileBody screenShot3 = new FileBody(mobileApplicationBean.getScreenShot3File()); reqEntity.addPart("screenshot3File", screenShot3); reqEntity.addPart("addNewAssetButton", new StringBody("Submit", ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("mobileapp", new StringBody(mobileApplicationBean.getMobileapp(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("sso_ssoProvider", new StringBody(mobileApplicationBean.getSso_ssoProvider(), ContentType.MULTIPART_FORM_DATA)); reqEntity.addPart("appmeta", new StringBody(mobileApplicationBean.getAppmeta(), ContentType.MULTIPART_FORM_DATA)); final HttpEntity entity = reqEntity.build(); httpPost.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = ""; try { responseBody = httpClient.execute(httpPost, responseHandler); } catch (Exception e) { e.printStackTrace(); } return responseBody; }
From source file:co.aurasphere.botmill.fb.internal.util.network.NetworkUtils.java
/** * POSTs a message as a JSON string to Facebook. * * @param recipient/*ww w. j a v a 2s. c o m*/ * the recipient * @param type * the type * @param file * the file */ public static void postFormDataMessage(String recipient, AttachmentType type, File file) { String pageToken = FbBotMillContext.getInstance().getPageToken(); // If the page token is invalid, returns. if (!validatePageToken(pageToken)) { return; } // TODO: add checks for valid attachmentTypes (FILE, AUDIO or VIDEO) HttpPost post = new HttpPost(FbBotMillNetworkConstants.FACEBOOK_BASE_URL + FbBotMillNetworkConstants.FACEBOOK_MESSAGES_URL + pageToken); FileBody filedata = new FileBody(file); StringBody recipientPart = new StringBody("{\"id\":\"" + recipient + "\"}", ContentType.MULTIPART_FORM_DATA); StringBody messagePart = new StringBody( "{\"attachment\":{\"type\":\"" + type.name().toLowerCase() + "\", \"payload\":{}}}", ContentType.MULTIPART_FORM_DATA); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.STRICT); builder.addPart("recipient", recipientPart); builder.addPart("message", messagePart); // builder.addPart("filedata", filedata); builder.addBinaryBody("filedata", file); builder.setContentType(ContentType.MULTIPART_FORM_DATA); // builder.setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW"); HttpEntity entity = builder.build(); post.setEntity(entity); // Logs the raw JSON for debug purposes. BufferedReader br; // post.addHeader("Content-Type", "multipart/form-data"); try { // br = new BufferedReader(new InputStreamReader( // ()))); Header[] allHeaders = post.getAllHeaders(); for (Header h : allHeaders) { logger.debug("Header {} -> {}", h.getName(), h.getValue()); } // String output = br.readLine(); } catch (Exception e) { e.printStackTrace(); } send(post); }
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 w w w . j a v a 2 s . c o 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.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 w w w .j a va 2s .co 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: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 w w w .j a va 2 s. c om*/ 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:com.adobe.aem.demo.communities.Loader.java
private static String doThumbnail(String hostname, String port, String adminPassword, String csvfile, String filename) {//from w w w . j a v a 2s .co m 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"; }