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.neighbor.ex.tong.network.UploadFileAndMessage.java
@Override protected Void doInBackground(Void... voids) { try {/*ww w . j av a2 s . c o m*/ MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addTextBody("message", URLEncoder.encode(message, "UTF-8"), ContentType.create("Multipart/related", "UTF-8")); builder.addPart("image", new FileBody(new File(path))); InputStream inputStream = null; HttpClient httpClient = AndroidHttpClient.newInstance("Android"); String carNo = prefs.getString(CONST.ACCOUNT_LICENSE, ""); String encodeCarNo = ""; if (false == carNo.equals("")) { encodeCarNo = URLEncoder.encode(carNo, "UTF-8"); } HttpPost httpPost = new HttpPost(UPLAOD_URL + encodeCarNo); httpPost.setEntity(builder.build()); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); inputStream = httpEntity.getContent(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); StringBuilder stringBuilder = new StringBuilder(); String line = null; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line + "\n"); } inputStream.close(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:org.wisdom.framework.vertx.FormTest.java
@Test public void testFormSubmissionAsMultipart() throws InterruptedException, IOException { Router router = prepareServer();/* w w w . j a va 2 s . co m*/ // Prepare the router with a controller Controller controller = new DefaultController() { @SuppressWarnings("unused") public Result submit() { final Map<String, List<String>> form = context().form(); // String if (!form.get("key").get(0).equals("value")) { return badRequest("key is not equals to value"); } // Multiple values List<String> list = form.get("list"); if (!(list.contains("1") && list.contains("2"))) { return badRequest("list does not contains 1 and 2"); } return ok(context().header(HeaderNames.CONTENT_TYPE)); } }; Route route = new RouteBuilder().route(HttpMethod.POST).on("/").to(controller, "submit"); when(router.getRouteFor(anyString(), anyString(), any(org.wisdom.api.http.Request.class))) .thenReturn(route); server.start(); waitForStart(server); int port = server.httpPort(); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("key", "value", ContentType.TEXT_PLAIN).addTextBody("list", "1", ContentType.TEXT_PLAIN) .addTextBody("list", "2", ContentType.TEXT_PLAIN); final HttpResponse response = Request.Post("http://localhost:" + port + "/").body(builder.build()).execute() .returnResponse(); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200); assertThat(EntityUtils.toString(response.getEntity())).contains(MimeTypes.MULTIPART); }
From source file:com.frochr123.fabqr.FabQRFunctions.java
public static void uploadFabQRProject(String name, String email, String projectName, int licenseIndex, String tools, String description, String location, BufferedImage imageReal, BufferedImage imageScheme, PlfFile plfFile, String lasercutterName, String lasercutterMaterial) throws Exception { // Check for valid situation, otherwise abort if (MainView.getInstance() == null || VisicutModel.getInstance() == null || VisicutModel.getInstance().getPlfFile() == null || !isFabqrActive() || getFabqrPrivateURL() == null || getFabqrPrivateURL().isEmpty() || MaterialManager.getInstance() == null || MappingManager.getInstance() == null || VisicutModel.getInstance().getSelectedLaserDevice() == null) { throw new Exception("FabQR upload exception: Critical error"); }//from w w w . j ava2 s . c om // Check valid data if (name == null || email == null || projectName == null || projectName.length() < 3 || licenseIndex < 0 || tools == null || tools.isEmpty() || description == null || description.isEmpty() || location == null || location.isEmpty() || imageScheme == null || plfFile == null || lasercutterName == null || lasercutterName.isEmpty() || lasercutterMaterial == null || lasercutterMaterial.isEmpty()) { throw new Exception("FabQR upload exception: Invalid input data"); } // Convert images to byte data for PNG, imageReal is allowed to be empty byte[] imageSchemeBytes = null; ByteArrayOutputStream imageSchemeOutputStream = new ByteArrayOutputStream(); PreviewImageExport.writePngToOutputStream(imageSchemeOutputStream, imageScheme); imageSchemeBytes = imageSchemeOutputStream.toByteArray(); if (imageSchemeBytes == null) { throw new Exception("FabQR upload exception: Error converting scheme image"); } byte[] imageRealBytes = null; if (imageReal != null) { // Need to convert image, ImageIO.write messes up the color space of the original input image BufferedImage convertedImage = new BufferedImage(imageReal.getWidth(), imageReal.getHeight(), BufferedImage.TYPE_3BYTE_BGR); ColorConvertOp op = new ColorConvertOp(null); op.filter(imageReal, convertedImage); ByteArrayOutputStream imageRealOutputStream = new ByteArrayOutputStream(); ImageIO.write(convertedImage, "jpg", imageRealOutputStream); imageRealBytes = imageRealOutputStream.toByteArray(); } // Extract all URLs from used QR codes List<String> referencesList = new LinkedList<String>(); List<PlfPart> plfParts = plfFile.getPartsCopy(); for (PlfPart plfPart : plfParts) { if (plfPart.getQRCodeInfo() != null && plfPart.getQRCodeInfo().getQRCodeSourceURL() != null && !plfPart.getQRCodeInfo().getQRCodeSourceURL().trim().isEmpty()) { // Process url, if it is URL of a FabQR system, remove download flag and point to project page instead // Use regex to check for FabQR system URL structure String qrCodeUrl = plfPart.getQRCodeInfo().getQRCodeSourceURL().trim(); // Check for temporary URL structure of FabQR system Pattern fabQRUrlTemporaryPattern = Pattern .compile("^https{0,1}://.*?" + "/" + FABQR_TEMPORARY_MARKER + "/" + "([a-z]|[0-9]){7,7}$"); // Do not include link if it is just temporary if (fabQRUrlTemporaryPattern.matcher(qrCodeUrl).find()) { continue; } // Check for download URL structure of FabQR system // Change URL to point to project page instead Pattern fabQRUrlDownloadPattern = Pattern .compile("^https{0,1}://.*?" + "/" + FABQR_DOWNLOAD_MARKER + "/" + "([a-z]|[0-9]){7,7}$"); if (fabQRUrlDownloadPattern.matcher(qrCodeUrl).find()) { qrCodeUrl = qrCodeUrl.replace("/" + FABQR_DOWNLOAD_MARKER + "/", "/"); } // Add URL if it is not yet in list if (!referencesList.contains(qrCodeUrl)) { referencesList.add(qrCodeUrl); } } } String references = ""; for (String ref : referencesList) { // Add comma for non first entries if (!references.isEmpty()) { references = references + ","; } references = references + ref; } // Get bytes for PLF file byte[] plfFileBytes = null; ByteArrayOutputStream plfFileOutputStream = new ByteArrayOutputStream(); VisicutModel.getInstance().savePlfToStream(MaterialManager.getInstance(), MappingManager.getInstance(), plfFileOutputStream); plfFileBytes = plfFileOutputStream.toByteArray(); if (plfFileBytes == null) { throw new Exception("FabQR upload exception: Error saving PLF file"); } // Begin uploading data String uploadUrl = getFabqrPrivateURL() + FABQR_API_UPLOAD_PROJECT; // Create HTTP client and cusomized config for timeouts CloseableHttpClient httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(FABQR_UPLOAD_TIMEOUT) .setConnectTimeout(FABQR_UPLOAD_TIMEOUT).setConnectionRequestTimeout(FABQR_UPLOAD_TIMEOUT).build(); // Create HTTP Post request and entity builder HttpPost httpPost = new HttpPost(uploadUrl); httpPost.setConfig(requestConfig); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); // Insert file uploads multipartEntityBuilder.addBinaryBody("imageScheme", imageSchemeBytes, ContentType.APPLICATION_OCTET_STREAM, "imageScheme.png"); multipartEntityBuilder.addBinaryBody("inputFile", plfFileBytes, ContentType.APPLICATION_OCTET_STREAM, "inputFile.plf"); // Image real is allowed to be null, if it is not, send it if (imageRealBytes != null) { multipartEntityBuilder.addBinaryBody("imageReal", imageRealBytes, ContentType.APPLICATION_OCTET_STREAM, "imageReal.png"); } // Prepare content type for text data, especially needed for correct UTF8 encoding ContentType contentType = ContentType.create("text/plain", Consts.UTF_8); // Insert text data multipartEntityBuilder.addTextBody("name", name, contentType); multipartEntityBuilder.addTextBody("email", email, contentType); multipartEntityBuilder.addTextBody("projectName", projectName, contentType); multipartEntityBuilder.addTextBody("licenseIndex", new Integer(licenseIndex).toString(), contentType); multipartEntityBuilder.addTextBody("tools", tools, contentType); multipartEntityBuilder.addTextBody("description", description, contentType); multipartEntityBuilder.addTextBody("location", location, contentType); multipartEntityBuilder.addTextBody("lasercutterName", lasercutterName, contentType); multipartEntityBuilder.addTextBody("lasercutterMaterial", lasercutterMaterial, contentType); multipartEntityBuilder.addTextBody("references", references, contentType); // Assign entity to this post request HttpEntity httpEntity = multipartEntityBuilder.build(); httpPost.setEntity(httpEntity); // Set authentication information String encodedCredentials = Helper.getEncodedCredentials(FabQRFunctions.getFabqrPrivateUser(), FabQRFunctions.getFabqrPrivatePassword()); if (!encodedCredentials.isEmpty()) { httpPost.addHeader("Authorization", "Basic " + encodedCredentials); } // Send request CloseableHttpResponse res = httpClient.execute(httpPost); // React to possible server side errors if (res.getStatusLine() == null || res.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new Exception("FabQR upload exception: Server sent wrong HTTP status code: " + new Integer(res.getStatusLine().getStatusCode()).toString()); } // Close everything correctly res.close(); httpClient.close(); }
From source file:utils.APIImporter.java
/** * update the content of a document of the API been sent * @param folderPath folder path to the imported API * @param uuid uuid of the API//from ww w . ja v a 2 s . c o m * @param response payload for the publishing document * @param accessToken access token */ private static void addDocumentContent(String folderPath, String uuid, String response, String accessToken) { String documentId = ImportExportUtils.readJsonValues(response, ImportExportConstants.DOC_ID); String sourceType = ImportExportUtils.readJsonValues(response, ImportExportConstants.SOURCE_TYPE); String documentName = ImportExportUtils.readJsonValues(response, ImportExportConstants.DOC_NAME); String directoryName; //setting directory name depending on the document source type if (sourceType.equals(ImportExportConstants.INLINE_DOC_TYPE)) { directoryName = ImportExportConstants.INLINE_DOCUMENT_DIRECTORY; } else { directoryName = ImportExportConstants.FILE_DOCUMENT_DIRECTORY; } //getting document content String documentContentPath = folderPath + ImportExportConstants.DIRECTORY_SEPARATOR + ImportExportConstants.DOCUMENT_DIRECTORY + ImportExportConstants.DIRECTORY_SEPARATOR + directoryName + ImportExportConstants.DIRECTORY_SEPARATOR + documentName; File content = new File(documentContentPath); HttpEntity entity = null; if (sourceType.equals(ImportExportConstants.FILE_DOC_TYPE)) { //adding file type content MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addBinaryBody(ImportExportConstants.MULTIPART_FILE, content); entity = multipartEntityBuilder.build(); } else { BufferedReader br = null; try { br = new BufferedReader(new FileReader(content)); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append("\n"); line = br.readLine(); } String inlineContent = sb.toString(); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addTextBody(ImportExportConstants.MULTIPART_Inline, inlineContent, ContentType.APPLICATION_OCTET_STREAM); entity = multipartEntityBuilder.build(); } catch (IOException e) { errorMsg = "error occurred while retrieving content of document " + ImportExportUtils.readJsonValues(response, ImportExportConstants.DOC_NAME); log.error(errorMsg, e); } finally { IOUtils.closeQuietly(br); } } String url = config.getPublisherUrl() + "apis/" + uuid + "/documents/" + documentId + "/content"; 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 uploading the content of document " + ImportExportUtils.readJsonValues(response, ImportExportConstants.DOC_NAME); log.error(errorMsg, e); } }
From source file:org.mule.module.http.functional.listener.HttpListenerAttachmentsTestCase.java
private HttpEntity getMultipartEntity(boolean withFile) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(TEXT_BODY_FIELD_NAME, TEXT_BODY_FIELD_VALUE, ContentType.TEXT_PLAIN); if (withFile) { builder.addBinaryBody(FILE_BODY_FIELD_NAME, FILE_BODY_FIELD_VALUE.getBytes(), ContentType.APPLICATION_OCTET_STREAM, FIELD_BDOY_FILE_NAME); }/*from w w w . ja va 2 s .c om*/ return builder.build(); }
From source file:com.github.fabienbarbero.flickr.api.CommandArguments.java
public HttpEntity getBody(Map<String, String> additionalParameters) { MultipartEntityBuilder entity = MultipartEntityBuilder.create(); for (Parameter param : params) { if (!param.internal) { if (param.value instanceof File) { entity.addBinaryBody(param.key, (File) param.value); } else if (param.value instanceof String) { entity.addTextBody(param.key, (String) param.value, CT_TEXT); }//www. ja v a 2s . c o m } } for (Map.Entry<String, String> entry : additionalParameters.entrySet()) { entity.addTextBody(entry.getKey(), entry.getValue(), CT_TEXT); } return entity.build(); }
From source file:edu.si.services.sidora.rest.batch.BatchServiceTest.java
@Test public void newBatchRequest_addResourceObjects_Test() throws Exception { String resourceListXML = FileUtils .readFileToString(new File("src/test/resources/test-data/batch-test-files/audio/audioFiles.xml")); String expectedHTTPResponseBody = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<Batch>\n" + " <ParentPID>" + parentPid + "</ParentPID>\n" + " <CorrelationID>" + correlationId + "</CorrelationID>\n" + "</Batch>\n"; BatchRequestResponse expectedCamelResponseBody = new BatchRequestResponse(); expectedCamelResponseBody.setParentPID(parentPid); expectedCamelResponseBody.setCorrelationId(correlationId); MockEndpoint mockEndpoint = getMockEndpoint("mock:result"); mockEndpoint.expectedMessageCount(1); context.getComponent("sql", SqlComponent.class).setDataSource(db); context.getRouteDefinition("BatchProcessResources").autoStartup(false); //Configure and use adviceWith to mock for testing purpose context.getRouteDefinition("BatchProcessAddResourceObjects").adviceWith(context, new AdviceWithRouteBuilder() { @Override/*from w ww.j a va 2s .co m*/ public void configure() throws Exception { weaveById("httpGetResourceList").replace().setBody(simple(resourceListXML)); weaveByToString(".*bean:batchRequestControllerBean.*").replace().setHeader("correlationId", simple(correlationId)); weaveAddLast().to("mock:result"); } }); HttpPost post = new HttpPost(BASE_URL + "/addResourceObjects/" + parentPid); MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.STRICT); // Add filelist xml URL upload builder.addTextBody("resourceFileList", resourceFileList, ContentType.TEXT_PLAIN); // Add metadata xml file URL upload builder.addTextBody("ds_metadata", ds_metadata, ContentType.TEXT_PLAIN); // Add sidora xml URL upload builder.addTextBody("ds_sidora", ds_sidora, ContentType.TEXT_PLAIN); // Add association xml URL upload builder.addTextBody("association", association, ContentType.TEXT_PLAIN); // Add resourceOwner string builder.addTextBody("resourceOwner", resourceOwner, ContentType.TEXT_PLAIN); post.setEntity(builder.build()); HttpResponse response = httpClient.execute(post); assertEquals(200, response.getStatusLine().getStatusCode()); String responseBody = EntityUtils.toString(response.getEntity()); log.debug("======================== [ RESPONSE ] ========================\n" + responseBody); assertEquals(expectedHTTPResponseBody, responseBody); log.debug("===============[ DB Requests ]================\n{}", jdbcTemplate.queryForList("select * from sidora.camelBatchRequests")); log.debug("===============[ DB Resources ]===============\n{}", jdbcTemplate.queryForList("select * from sidora.camelBatchResources")); BatchRequestResponse camelResultBody = (BatchRequestResponse) mockEndpoint.getExchanges().get(0).getIn() .getBody(); assertIsInstanceOf(BatchRequestResponse.class, camelResultBody); assertEquals(camelResultBody.getParentPID(), parentPid); assertEquals(camelResultBody.getCorrelationId(), correlationId); assertMockEndpointsSatisfied(); }
From source file:com.movilizer.mds.webservice.models.MovilizerUploadForm.java
private MultipartEntityBuilder getForm(long systemId, String password, String pool, String key, String lang, String suffix, String ack) { MultipartEntityBuilder form = MultipartEntityBuilder.create() .addTextBody("systemId", String.valueOf(systemId), ContentType.TEXT_PLAIN) .addTextBody("password", password, ContentType.TEXT_PLAIN) .addTextBody("pool", pool, ContentType.TEXT_PLAIN).addTextBody("key", key, ContentType.TEXT_PLAIN) .addTextBody("suffix", suffix, ContentType.TEXT_PLAIN); if (lang != null) { form.addTextBody("lang", lang, ContentType.TEXT_PLAIN); }/*www . ja va 2 s. co m*/ if (ack != null) { form.addTextBody("ack", suffix, ContentType.TEXT_PLAIN); } return form; }
From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.patch.QMetryRestWebservice.java
/** * attach log using run id//from w w w. j a va 2 s . c o m * * @param token * - token generate using username and password * @param projectID * @param releaseID * @param cycleID * @param testCaseRunId * @param filePath * - absolute path of file to be attached * @return */ public int attachTestLogsUsingRunId(String token, String projectID, String releaseID, String cycleID, 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(baseURL + "/rest/attachments/testLog"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody bin = new FileBody(filePath); builder.addTextBody("desc", "Attached on " + CurrentDate, ContentType.TEXT_PLAIN); builder.addTextBody("type", "TCR", ContentType.TEXT_PLAIN); builder.addTextBody("entityId", String.valueOf(testCaseRunId), ContentType.TEXT_PLAIN); builder.addPart("file", bin); HttpEntity reqEntity = builder.build(); httppost.setEntity(reqEntity); httppost.addHeader("usertoken", token); httppost.addHeader("scope", projectID + ":" + releaseID + ":" + cycleID); 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:at.gv.egiz.sl.util.BKUSLConnector.java
private String performHttpBulkRequestToBKU(String xmlRequest, BulkRequestPackage pack, SignParameter parameter) throws ClientProtocolException, IOException, IllegalStateException { CloseableHttpClient client = null;// ww w .j a v a 2 s . c o m try { client = buildHttpClient(); HttpPost post = new HttpPost(this.bkuUrl); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setCharset(Charset.forName("UTF-8")); entityBuilder.addTextBody(XMLREQUEST, xmlRequest, ContentType.TEXT_XML.withCharset(Charset.forName("UTF-8"))); if (parameter != null) { String transactionId = parameter.getTransactionId(); if (transactionId != null) { entityBuilder.addTextBody("TransactionId_", transactionId); } } for (SignRequestPackage signRequestPackage : pack.getSignRequestPackages()) { if (pack != null && signRequestPackage != null && signRequestPackage.getCmsRequest().getSignatureData() != null) { entityBuilder.addBinaryBody("fileupload", PDFUtils.blackOutSignature(signRequestPackage.getCmsRequest().getSignatureData(), signRequestPackage.getCmsRequest().getByteRange())); } } post.setEntity(entityBuilder.build()); HttpResponse response = client.execute(post); logger.debug("Response Code : " + response.getStatusLine().getStatusCode()); if (parameter instanceof BKUHeaderHolder) { BKUHeaderHolder holder = (BKUHeaderHolder) parameter; Header[] headers = response.getAllHeaders(); if (headers != null) { for (int i = 0; i < headers.length; i++) { BKUHeader hdr = new BKUHeader(headers[i].getName(), headers[i].getValue()); logger.debug("Response Header : {}", hdr.toString()); holder.getProcessInfo().add(hdr); } } BKUHeader hdr = new BKUHeader(ErrorConstants.STATUS_INFO_SIGDEVICE, SIGNATURE_DEVICE); logger.debug("Response Header : {}", hdr.toString()); holder.getProcessInfo().add(hdr); } BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } rd.close(); response = null; rd = null; logger.trace(result.toString()); return result.toString(); } catch (PDFIOException e) { throw new PdfAsWrappedIOException(e); } finally { if (client != null) { client.close(); } } }