List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder create
public static MultipartEntityBuilder create()
From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.QMetryRestWebservice.java
/** * attach log using run id/*from ww w .j a va2s . 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:aajavafx.VisitorController.java
@FXML private void handleSave(ActionEvent event) { if (imageFile != null) { String visitorId = visitorIDField.getText(); visitorIDField.clear();/*from w ww . j av a 2 s . c o m*/ String firstName = firstNameField.getText(); firstNameField.clear(); String lastName = lastNameField.getText(); lastNameField.clear(); String email = emailField.getText(); emailField.clear(); String phoneNumber = phoneNumberField.getText(); phoneNumberField.clear(); Integer companyId = getCompanyIDFromName(companyBox.getValue().toString()); try { Gson gson = new Gson(); HttpClient httpClient = HttpClientBuilder.create().build(); HttpEntityEnclosingRequestBase HttpEntity = null; //this is the superclass for post, put, get, etc if (visitorIDField.isEditable()) { //then we are posting a new record HttpEntity = new HttpPost(VisitorsRootURL); //so make a http post object } else { //we are editing a record HttpEntity = new HttpPut(VisitorsRootURL); //so make a http put object } Company company = getCompany(companyId); Visitors visitor = new Visitors(visitorId, firstName, lastName, email, phoneNumber, company); String jsonString = new String(gson.toJson(visitor)); System.out.println("json string: " + jsonString); StringEntity postString = new StringEntity(jsonString); HttpEntity.setEntity(postString); HttpEntity.setHeader("Content-type", "application/json"); HttpResponse response = httpClient.execute(HttpEntity); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 204) { System.out.println("New visitor posted successfully"); } else { System.out.println("Server error: " + response.getStatusLine()); } visitorIDField.setEditable(false); firstNameField.setEditable(false); lastNameField.setEditable(false); emailField.setEditable(false); phoneNumberField.setEditable(false); companyBox.setEditable(false); visitorIDField.clear(); firstNameField.clear(); lastNameField.clear(); emailField.clear(); tableVisitors.setItems(getVisitors()); } catch (UnsupportedEncodingException ex) { System.out.println(ex); } catch (IOException e) { System.out.println(e); } catch (JSONException je) { System.out.println("JSON error: " + je); } FileInputStream fis = null; try { fis = new FileInputStream(imageFile); HttpClient httpClient = HttpClientBuilder.create().build(); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); FileBody fileBody = new FileBody(new File(imageFile.getName())); //image should be a String builder.addPart("file", new InputStreamBody(fis, imageFile.getName())); //builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // server back-end URL HttpPost httppost = new HttpPost(postHTML); //MultipartEntity entity = new MultipartEntity(); // set the file input stream and file name as arguments //entity.addPart("file", new InputStreamBody(fis, inFile.getName())); HttpEntity entity = builder.build(); httppost.setEntity(entity); // execute the request HttpResponse response = httpClient.execute(httppost); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity responseEntity = response.getEntity(); String responseString = EntityUtils.toString(responseEntity, "UTF-8"); System.out.println("[" + statusCode + "] " + responseString); } catch (ClientProtocolException e) { System.err.println("Unable to make connection"); e.printStackTrace(); } catch (IOException e) { System.err.println("Unable to read file"); e.printStackTrace(); } finally { try { if (fis != null) fis.close(); } catch (IOException e) { } } } else { errorLabel.setText("Record Not Saved: Please attach a photo for this visitor"); errorLabel.setVisible(true); } }
From source file:com.ibm.ws.lars.rest.RepositoryContext.java
public String doPostMultipart(String url, String name, String json, byte[] content, ContentType contentType, int expectedStatusCode) throws ClientProtocolException, IOException { HttpPost post = new HttpPost(fullURL + url); HttpEntity requestEntity = MultipartEntityBuilder.create() .addPart("attachmentInfo", new StringBody(json, ContentType.APPLICATION_JSON)) .addPart(name, new ByteArrayBody(content, contentType, name)).build(); post.setEntity(requestEntity);//from w w w. j a v a 2s . c o m return doRequest(post, expectedStatusCode); }
From source file:utils.APIImporter.java
private static void addAPIImage(String folderPath, String accessToken, String uuid) { File apiFolder = new File(folderPath); File[] fileArray = apiFolder.listFiles(); if (fileArray != null) { for (File file : fileArray) { String fileName = file.getName(); String imageName = fileName.substring(0, fileName.indexOf(".")); if (imageName.equalsIgnoreCase(ImportExportConstants.IMG_NAME)) { File imageFile = new File(folderPath + ImportExportConstants.ZIP_FILE_SEPARATOR + fileName); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addBinaryBody(ImportExportConstants.MULTIPART_FILE, imageFile); HttpEntity entity = multipartEntityBuilder.build(); String url = config.getPublisherUrl() + "apis/" + uuid + "/thumbnail"; CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate()); HttpPost request = new HttpPost(url); request.setHeader(HttpHeaders.AUTHORIZATION, ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + accessToken); request.setEntity(entity); try { client.execute(request); } catch (IOException e) { errorMsg = "Error occurred while publishing the API thumbnail"; log.error(errorMsg, e); }/* w ww . j a va2 s . c o m*/ break; } } } }
From source file:org.apache.sling.etcd.client.impl.EtcdClientImpl.java
@Nonnull private HttpUriRequest entity(@Nonnull HttpEntityEnclosingRequestBase method, @Nonnull InputStream value) { method.setEntity(MultipartEntityBuilder.create().addBinaryBody("value", value).build()); return method; }
From source file:org.openestate.is24.restapi.hc43.HttpComponents43Client.java
@Override protected Response sendVideoUploadRequest(URL url, RequestMethod method, String auth, InputStream input, String fileName, final long fileSize) throws IOException, OAuthException { if (method == null) method = RequestMethod.POST;/*from w w w. j a v a 2s . c om*/ if (!RequestMethod.POST.equals(method) && !RequestMethod.PUT.equals(method)) throw new IllegalArgumentException("Invalid request method!"); HttpUriRequest request = null; if (RequestMethod.POST.equals(method)) { request = new HttpPost(url.toString()); } else if (RequestMethod.PUT.equals(method)) { request = new HttpPut(url.toString()); } else { throw new IOException("Unsupported request method '" + method + "'!"); } MultipartEntityBuilder b = MultipartEntityBuilder.create(); // add auth part to the multipart entity auth = StringUtils.trimToNull(auth); if (auth != null) { //StringBody authPart = new StringBody( // auth, ContentType.create( "text/plain", getEncoding() ) ); //b.addPart( "auth", authPart ); b.addTextBody("auth", auth, ContentType.create("text/plain", getEncoding())); } // add file part to the multipart entity if (input != null) { fileName = StringUtils.trimToNull(fileName); if (fileName == null) fileName = "upload.bin"; //InputStreamBody filePart = new InputStreamBody( input, fileName ); InputStreamBody filePart = new InputStreamBodyWithLength(input, fileName, fileSize); b.addPart("videofile", filePart); } // add multipart entity to the request HttpEntity requestMultipartEntity = b.build(); request.setHeader("MIME-Version", "1.0"); request.addHeader(requestMultipartEntity.getContentType()); request.setHeader("Content-Language", "en-US"); request.setHeader("Accept-Charset", "UTF-8"); request.setHeader("Accept-Encoding", "gzip,deflate"); request.setHeader("Connection", "close"); ((HttpEntityEnclosingRequest) request).setEntity(requestMultipartEntity); // sign request //getAuthConsumer().sign( request ); // send request HttpResponse response = httpClient.execute(request); // create response return createResponse(response); }
From source file:org.wso2.store.client.ArtifactPublisher.java
/** * Upload assets to ES//from w w w . j av a 2s . c om * POST asset details to asset upload REST API * If attribute is a physical file seek a file in a resources directory and upload as multipart attachment. * @param assetArr Array of assets * @param dir resource files directory */ private void uploadAssets(Asset[] assetArr, File dir) { HashMap<String, String> attrMap; MultipartEntityBuilder multiPartBuilder; List<String> fileAttributes; File imageFile; String responseJson; StringBuilder publisherUrlBuilder; String uploadUrl = hostUrl + ArtifactUploadClientConstants.PUBLISHER_URL + "/"; HttpPost httpPost; CloseableHttpClient httpClient = clientBuilder.build(); CloseableHttpResponse response = null; for (Asset asset : assetArr) { publisherUrlBuilder = new StringBuilder(); if (asset.getId() != null) { publisherUrlBuilder.append(uploadUrl).append(asset.getId()).append("?type=") .append(asset.getType()); } else { publisherUrlBuilder.append(uploadUrl).append("?type=").append(asset.getType()); } multiPartBuilder = MultipartEntityBuilder.create(); multiPartBuilder.addTextBody("sessionId", sessionId); multiPartBuilder.addTextBody("asset", gson.toJson(asset)); attrMap = asset.getAttributes(); httpPost = new HttpPost(publisherUrlBuilder.toString()); //get file type attributes list for asset type fileAttributes = rxtFileAttributesMap.get(asset.getType()); for (String attrKey : attrMap.keySet()) { //check attribute one by one whether is it a file type if (fileAttributes != null && fileAttributes.contains(attrKey)) { imageFile = new File(dir + File.separator + ArtifactUploadClientConstants.RESOURCE_DIR_NAME + File.separator + attrMap.get(attrKey)); multiPartBuilder.addBinaryBody(attrKey, imageFile); } } httpPost.setEntity(multiPartBuilder.build()); try { response = httpClient.execute(httpPost, httpContext); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) { log.info("Asset " + asset.getName() + " uploaded successfully"); } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) { log.info("Asset " + asset.getName() + " updated successfully"); } else { responseJson = EntityUtils.toString(response.getEntity()); log.info("Asset " + asset.getName() + " not uploaded successfully " + responseJson); } } catch (IOException ex) { log.error("Asset Id:" + asset.getId() + " Name;" + asset.getName()); log.error("Error in asset Upload", ex); log.debug("Asset upload fail:" + asset); } finally { IOUtils.closeQuietly(response); } } IOUtils.closeQuietly(response); IOUtils.closeQuietly(httpClient); }
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 w w . j a v a 2s . c om @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:de.tu_dortmund.ub.data.dswarm.Init.java
/** * uploads a file and creates a data resource with it * * @param filename//from w w w . jav a2 s.c om * @param name * @param description * @return responseJson * @throws Exception */ private String uploadFileAndCreateResource(final String filename, final String name, final String description, final String serviceName, final String engineDswarmAPI) throws Exception { try (final CloseableHttpClient httpclient = HttpClients.createDefault()) { final HttpPost httpPost = new HttpPost(engineDswarmAPI + DswarmBackendStatics.RESOURCES_ENDPOINT); final File file1 = new File(filename); final FileBody fileBody = new FileBody(file1); final StringBody stringBodyForName = new StringBody(name, ContentType.TEXT_PLAIN); final StringBody stringBodyForDescription = new StringBody(description, ContentType.TEXT_PLAIN); final HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart(DswarmBackendStatics.NAME_IDENTIFIER, stringBodyForName) .addPart(DswarmBackendStatics.DESCRIPTION_IDENTIFIER, stringBodyForDescription) .addPart(FILE_IDENTIFIER, fileBody).build(); httpPost.setEntity(reqEntity); LOG.info(String.format("[%s][%d] request : %s", serviceName, cnt, httpPost.getRequestLine())); try (final CloseableHttpResponse httpResponse = httpclient.execute(httpPost)) { final int statusCode = httpResponse.getStatusLine().getStatusCode(); final HttpEntity httpEntity = httpResponse.getEntity(); final String message = String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode, httpResponse.getStatusLine().getReasonPhrase()); switch (statusCode) { case 201: { LOG.info(message); final StringWriter writer = new StringWriter(); IOUtils.copy(httpEntity.getContent(), writer, APIStatics.UTF_8); final String responseJson = writer.toString(); writer.flush(); writer.close(); LOG.debug(String.format("[%s][%d] responseJson : %s", serviceName, cnt, responseJson)); return responseJson; } default: { LOG.error(message); EntityUtils.consume(httpEntity); throw new Exception("something went wrong at resource upload: " + message); } } } } }