Java Code Examples for org.apache.http.entity.mime.MultipartEntityBuilder#setMode()
The following examples show how to use
org.apache.http.entity.mime.MultipartEntityBuilder#setMode() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpClientPool.java From message_interface with MIT License | 7 votes |
public String uploadFile(String url, String path) throws IOException { HttpPost post = new HttpPost(url); try { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody fileBody = new FileBody(new File(path)); //image should be a String builder.addPart("file", fileBody); post.setEntity(builder.build()); CloseableHttpResponse response = client.execute(post); return readResponse(response); } finally { post.releaseConnection(); } }
Example 2
Source File: ClassTest.java From clouddisk with MIT License | 6 votes |
public static void main(String args[]){ HttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://localhost:8080/sso-web/upload"); httpPost.addHeader("Range","bytes=10000-"); final MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); multipartEntity.setCharset(Consts.UTF_8); multipartEntity.setMode(HttpMultipartMode.STRICT); multipartEntity.addBinaryBody("file", new File("/Users/huanghuanlai/Desktop/test.java")); httpPost.setEntity(multipartEntity.build()); try { HttpResponse response = httpClient.execute(httpPost); } catch (IOException e) { e.printStackTrace(); } }
Example 3
Source File: HttpClientMultipartLiveTest.java From tutorials with MIT License | 6 votes |
@Test public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException { final URL url = Thread.currentThread() .getContextClassLoader() .getResource("uploads/" + TEXTFILENAME); final File file = new File(url.getPath()); final String message = "This is a multipart post"; final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, TEXTFILENAME); builder.addTextBody("text", message, ContentType.DEFAULT_BINARY); final HttpEntity entity = builder.build(); post.setEntity(entity); response = client.execute(post); final int statusCode = response.getStatusLine() .getStatusCode(); final String responseString = getContent(); final String contentTypeInHeader = getContentTypeHeader(); assertThat(statusCode, equalTo(HttpStatus.SC_OK)); // assertTrue(responseString.contains("Content-Type: multipart/form-data;")); assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); System.out.println(responseString); System.out.println("POST Content Type: " + contentTypeInHeader); }
Example 4
Source File: HttpClientMultipartLiveTest.java From tutorials with MIT License | 6 votes |
@Test public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { final String message = "This is a multipart post"; final byte[] bytes = "binary code".getBytes(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addBinaryBody("file", bytes, ContentType.DEFAULT_BINARY, TEXTFILENAME); builder.addTextBody("text", message, ContentType.TEXT_PLAIN); final HttpEntity entity = builder.build(); post.setEntity(entity); response = client.execute(post); final int statusCode = response.getStatusLine() .getStatusCode(); final String responseString = getContent(); final String contentTypeInHeader = getContentTypeHeader(); assertThat(statusCode, equalTo(HttpStatus.SC_OK)); // assertTrue(responseString.contains("Content-Type: multipart/form-data;")); assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); System.out.println(responseString); System.out.println("POST Content Type: " + contentTypeInHeader); }
Example 5
Source File: UploadAPITest.java From blynk-server with GNU General Public License v3.0 | 5 votes |
private String upload(String filename) throws Exception { InputStream logoStream = UploadAPITest.class.getResourceAsStream("/" + filename); HttpPost post = new HttpPost("http://localhost:" + properties.getHttpPort() + "/upload"); ContentBody fileBody = new InputStreamBody(logoStream, ContentType.APPLICATION_OCTET_STREAM, filename); StringBody stringBody1 = new StringBody("Message 1", ContentType.MULTIPART_FORM_DATA); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("upfile", fileBody); builder.addPart("text1", stringBody1); HttpEntity entity = builder.build(); post.setEntity(entity); String staticPath; try (CloseableHttpResponse response = httpclient.execute(post)) { assertEquals(200, response.getStatusLine().getStatusCode()); staticPath = TestUtil.consumeText(response); assertNotNull(staticPath); assertTrue(staticPath.startsWith("/static")); assertTrue(staticPath.endsWith("bin")); } return staticPath; }
Example 6
Source File: HttpClientMultipartLiveTest.java From tutorials with MIT License | 5 votes |
@Test public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { final URL url = Thread.currentThread() .getContextClassLoader() .getResource("uploads/" + ZIPFILENAME); final URL url2 = Thread.currentThread() .getContextClassLoader() .getResource("uploads/" + IMAGEFILENAME); final InputStream inputStream = new FileInputStream(url.getPath()); final File file = new File(url2.getPath()); final String message = "This is a multipart post"; final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, IMAGEFILENAME); builder.addBinaryBody("upstream", inputStream, ContentType.create("application/zip"), ZIPFILENAME); builder.addTextBody("text", message, ContentType.TEXT_PLAIN); final HttpEntity entity = builder.build(); post.setEntity(entity); response = client.execute(post); final int statusCode = response.getStatusLine() .getStatusCode(); final String responseString = getContent(); final String contentTypeInHeader = getContentTypeHeader(); assertThat(statusCode, equalTo(HttpStatus.SC_OK)); // assertTrue(responseString.contains("Content-Type: multipart/form-data;")); assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); System.out.println(responseString); System.out.println("POST Content Type: " + contentTypeInHeader); inputStream.close(); }
Example 7
Source File: FormControllerTest.java From mangooio with Apache License 2.0 | 5 votes |
@Test public void testMultiFileUpload(@TempDir Path tempDir) throws IOException { // given String host = Application.getInstance(Config.class).getConnectorHttpHost(); int port = Application.getInstance(Config.class).getConnectorHttpPort(); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // when Path path1 = tempDir.resolve(UUID.randomUUID().toString()); Path path2 = tempDir.resolve(UUID.randomUUID().toString()); InputStream attachment1 = Resources.getResource("attachment.txt").openStream(); InputStream attachment2 = Resources.getResource("attachment.txt").openStream(); Files.copy(attachment1, path1); Files.copy(attachment2, path2); multipartEntityBuilder.addPart("attachment1", new FileBody(path1.toFile())); multipartEntityBuilder.addPart("attachment2", new FileBody(path2.toFile())); HttpPost httpPost = new HttpPost("http://" + host + ":" + port + "/multifile"); httpPost.setEntity(multipartEntityBuilder.build()); String response = null; HttpResponse httpResponse = httpClientBuilder.build().execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { response = EntityUtils.toString(httpEntity); } // then assertThat(httpResponse, not(nullValue())); assertThat(response, not(nullValue())); assertThat(httpResponse.getStatusLine().getStatusCode(), equalTo(StatusCodes.OK)); assertThat(response, equalTo("This is an attachmentThis is an attachment2")); }
Example 8
Source File: OTATest.java From blynk-server with GNU General Public License v3.0 | 5 votes |
@Test public void testOTAFailedWhenNoDevice() throws Exception { clientPair.hardwareClient.stop(); HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + clientPair.token); post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth)); String fileName = "test.bin"; InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName); ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("upfile", fileBody); HttpEntity entity = builder.build(); post.setEntity(entity); try (CloseableHttpResponse response = httpclient.execute(post)) { assertEquals(400, response.getStatusLine().getStatusCode()); String error = TestUtil.consumeText(response); assertNotNull(error); assertEquals("No device in session.", error); } }
Example 9
Source File: RESTJerseyPOSTFileClientTests.java From vxms with Apache License 2.0 | 5 votes |
@Test public void stringPOSTResponseWithParameter() throws InterruptedException, ExecutionException, IOException { File file = new File(getClass().getClassLoader().getResource("payload.xml").getFile()); HttpPost post = new HttpPost("http://" + HOST + ":" + PORT + SERVICE_REST_GET + "/simpleFilePOSTupload"); HttpClient client = HttpClientBuilder.create().build(); FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); StringBody stringBody1 = new StringBody("bar", ContentType.MULTIPART_FORM_DATA); StringBody stringBody2 = new StringBody("world", ContentType.MULTIPART_FORM_DATA); // MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("file", fileBody); builder.addPart("foo", stringBody1); builder.addPart("hello", stringBody2); HttpEntity entity = builder.build(); // post.setEntity(entity); HttpResponse response = client.execute(post); // Use createResponse object to verify upload success final String entity1 = convertStreamToString(response.getEntity().getContent()); System.out.println("-->" + entity1); assertTrue(entity1.equals("barworlddfgdfg")); testComplete(); }
Example 10
Source File: OTATest.java From blynk-server with GNU General Public License v3.0 | 5 votes |
@Test public void basicOTAForSingleUser() throws Exception { HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?user=" + getUserName()); post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth)); String fileName = "test.bin"; InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName); ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("upfile", fileBody); HttpEntity entity = builder.build(); post.setEntity(entity); String path; try (CloseableHttpResponse response = httpclient.execute(post)) { assertEquals(200, response.getStatusLine().getStatusCode()); path = TestUtil.consumeText(response); assertNotNull(path); assertTrue(path.startsWith("/static")); assertTrue(path.endsWith("bin")); } String responseUrl = "http://127.0.0.1:18080" + path; verify(clientPair.hardwareClient.responseMock, after(500).never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl))); TestHardClient newHardwareClient = new TestHardClient("localhost", properties.getHttpPort()); newHardwareClient.start(); newHardwareClient.login(clientPair.token); verify(newHardwareClient.responseMock, timeout(1000)).channelRead(any(), eq(ok(1))); newHardwareClient.reset(); newHardwareClient.send("internal " + b("ver 0.3.1 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 111")); verify(newHardwareClient.responseMock, timeout(500)).channelRead(any(), eq(ok(1))); verify(newHardwareClient.responseMock, timeout(500)).channelRead(any(), eq(internal(7777, "ota " + responseUrl))); }
Example 11
Source File: OTATest.java From blynk-server with GNU General Public License v3.0 | 5 votes |
@Test public void basicOTAForSingleUserAndNonExistingProject() throws Exception { HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?user=" + getUserName() + "&project=123"); post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth)); String fileName = "test.bin"; InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName); ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("upfile", fileBody); HttpEntity entity = builder.build(); post.setEntity(entity); String path; try (CloseableHttpResponse response = httpclient.execute(post)) { assertEquals(200, response.getStatusLine().getStatusCode()); path = TestUtil.consumeText(response); assertNotNull(path); assertTrue(path.startsWith("/static")); assertTrue(path.endsWith("bin")); } String responseUrl = "http://127.0.0.1:18080" + path; verify(clientPair.hardwareClient.responseMock, after(500).never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl))); TestHardClient newHardwareClient = new TestHardClient("localhost", properties.getHttpPort()); newHardwareClient.start(); newHardwareClient.login(clientPair.token); verify(newHardwareClient.responseMock, timeout(1000)).channelRead(any(), eq(ok(1))); newHardwareClient.reset(); newHardwareClient.send("internal " + b("ver 0.3.1 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 111")); verify(newHardwareClient.responseMock, timeout(500)).channelRead(any(), eq(ok(1))); verify(clientPair.hardwareClient.responseMock, never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl))); }
Example 12
Source File: OTATest.java From blynk-server with GNU General Public License v3.0 | 5 votes |
@Test public void basicOTAForSingleUserAndExistingProject() throws Exception { HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?user=" + getUserName() + "&project=My%20Dashboard"); post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth)); String fileName = "test.bin"; InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName); ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("upfile", fileBody); HttpEntity entity = builder.build(); post.setEntity(entity); String path; try (CloseableHttpResponse response = httpclient.execute(post)) { assertEquals(200, response.getStatusLine().getStatusCode()); path = TestUtil.consumeText(response); assertNotNull(path); assertTrue(path.startsWith("/static")); assertTrue(path.endsWith("bin")); } String responseUrl = "http://127.0.0.1:18080" + path; verify(clientPair.hardwareClient.responseMock, after(500).never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl))); TestHardClient newHardwareClient = new TestHardClient("localhost", properties.getHttpPort()); newHardwareClient.start(); newHardwareClient.login(clientPair.token); verify(newHardwareClient.responseMock, timeout(1000)).channelRead(any(), eq(ok(1))); newHardwareClient.reset(); newHardwareClient.send("internal " + b("ver 0.3.1 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 111")); verify(newHardwareClient.responseMock, timeout(500)).channelRead(any(), eq(ok(1))); verify(newHardwareClient.responseMock, timeout(500)).channelRead(any(), eq(internal(7777, "ota " + responseUrl))); }
Example 13
Source File: FormControllerTest.java From mangooio with Apache License 2.0 | 5 votes |
@Test public void testSingleFileUpload(@TempDir Path tempDir) throws IOException { // given String host = Application.getInstance(Config.class).getConnectorHttpHost(); int port = Application.getInstance(Config.class).getConnectorHttpPort(); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // when Path path = tempDir.resolve(UUID.randomUUID().toString()); InputStream attachment = Resources.getResource("attachment.txt").openStream(); Files.copy(attachment, path); multipartEntityBuilder.addPart("attachment", new FileBody(path.toFile())); HttpPost httpPost = new HttpPost("http://" + host + ":" + port + "/singlefile"); httpPost.setEntity(multipartEntityBuilder.build()); String response = null; HttpResponse httpResponse = httpClientBuilder.build().execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { response = EntityUtils.toString(httpEntity); } // then assertThat(httpResponse, not(nullValue())); assertThat(response, not(nullValue())); assertThat(httpResponse.getStatusLine().getStatusCode(), equalTo(StatusCodes.OK)); assertThat(response, equalTo("This is an attachment")); }
Example 14
Source File: HttpClientWrapper.java From TrackRay with GNU General Public License v3.0 | 5 votes |
/** * POST方式发送名值对请求URL,上传文件(包括图片) * * @param url * @return * @throws HttpException * @throws IOException */ public ResponseStatus postEntity(String url, String urlEncoding) throws HttpException, IOException { if (url == null) return null; HttpEntity entity = null; HttpRequestBase request = null; CloseableHttpResponse response = null; try { this.parseUrl(url); HttpPost httpPost = new HttpPost(toUrl()); //对请求的表单域进行填充 MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (NameValuePair nameValuePair : this.getNVBodies()) { entityBuilder.addPart(nameValuePair.getName(), new StringBody(nameValuePair.getValue(), ContentType.create("text/plain", urlEncoding))); } for (ContentBody contentBody : getContentBodies()) { entityBuilder.addPart("file", contentBody); } entityBuilder.setCharset(CharsetUtils.get(urlEncoding)); httpPost.setEntity(entityBuilder.build()); request = httpPost; response = client.execute(request); //响应状态 StatusLine statusLine = response.getStatusLine(); // 获取响应对象 entity = response.getEntity(); ResponseStatus ret = new ResponseStatus(); ret.setStatusCode(statusLine.getStatusCode()); getResponseStatus(entity, ret); return ret; } finally { close(entity, request, response); } }
Example 15
Source File: OTATest.java From blynk-server with GNU General Public License v3.0 | 4 votes |
@Test public void testImprovedUploadMethodAndCheckOTAStatusForDeviceThatWasOnline() throws Exception { clientPair.hardwareClient.send("internal " + b("ver 0.3.1 fm 0.3.3 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 111")); clientPair.hardwareClient.verifyResult(ok(1)); HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + clientPair.token); post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth)); String fileName = "test.bin"; InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName); ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("upfile", fileBody); HttpEntity entity = builder.build(); post.setEntity(entity); String path; try (CloseableHttpResponse response = httpclient.execute(post)) { assertEquals(200, response.getStatusLine().getStatusCode()); path = TestUtil.consumeText(response); assertNotNull(path); assertTrue(path.startsWith("/static")); assertTrue(path.endsWith("bin")); } String responseUrl = "http://127.0.0.1:18080" + path; verify(clientPair.hardwareClient.responseMock, timeout(500)).channelRead(any(), eq(internal(7777, "ota " + responseUrl))); clientPair.appClient.getDevice(1, 0); Device device = clientPair.appClient.parseDevice(1); assertNotNull(device); assertEquals("0.3.1", device.hardwareInfo.blynkVersion); assertEquals(10, device.hardwareInfo.heartbeatInterval); assertEquals("111", device.hardwareInfo.build); assertEquals("[email protected]", device.deviceOtaInfo.otaInitiatedBy); assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaInitiatedAt, 5000); assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaUpdateAt, 5000); clientPair.hardwareClient.send("internal " + b("ver 0.3.1 fm 0.3.3 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 112")); clientPair.hardwareClient.verifyResult(ok(2)); clientPair.appClient.getDevice(1, 0); device = clientPair.appClient.parseDevice(2); assertNotNull(device); assertEquals("0.3.1", device.hardwareInfo.blynkVersion); assertEquals(10, device.hardwareInfo.heartbeatInterval); assertEquals("112", device.hardwareInfo.build); assertEquals("[email protected]", device.deviceOtaInfo.otaInitiatedBy); assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaInitiatedAt, 5000); assertEquals(System.currentTimeMillis(), device.deviceOtaInfo.otaUpdateAt, 5000); }
Example 16
Source File: HttpRestWb.java From document-management-software with GNU Lesser General Public License v3.0 | 4 votes |
private static void uploadDocument(CloseableHttpClient httpclient) throws IOException { System.out.println("uploadDocument(CloseableHttpClient)"); URL url = new URL(BASE_PATH); HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin")); AuthCache authCache = new BasicAuthCache(); authCache.put(targetHost, new BasicScheme()); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); HttpPost httppost = new HttpPost(BASE_PATH + "/services/rest/document/upload"); File file = new File("c:/users/shatz/Downloads/logicaldocsecurity-171122130133.pdf"); //File file = new File("C:/tmp/InvoiceProcessing01-workflow.png"); System.out.println(file.getName()); System.out.println(file.getAbsolutePath()); long folderID = 124358812L; MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addTextBody("filename", file.getName(), ContentType.TEXT_PLAIN); builder.addBinaryBody("filedata", file, ContentType.DEFAULT_BINARY, file.getName()); builder.addTextBody("folderId", Long.toString(folderID), ContentType.TEXT_PLAIN); // HttpEntity entity = builder.build(); httppost.setEntity(entity); CloseableHttpResponse response = httpclient.execute(httppost, context); int code = response.getStatusLine().getStatusCode(); System.out.println("HTTPstatus code: "+ code); try { HttpEntity rent = response.getEntity(); if (rent != null) { String respoBody = EntityUtils.toString(rent, "UTF-8"); System.out.println(respoBody); } } finally { response.close(); } }
Example 17
Source File: RestJodConverter.java From document-management-software with GNU Lesser General Public License v3.0 | 4 votes |
public static void addPartMethod01() throws Exception { String textFileName = "C:/tmp/AnalisiTraffico.xlsx"; File file = new File(textFileName); //HttpPost post = new HttpPost("http://localhost:8080/jodapp/"); ///jodapp/converted/document.pdf HttpPost post = new HttpPost("http://localhost:8080/jodapp/converted/document.pdf"); FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); StringBody stringBody1 = new StringBody("pdf", ContentType.DEFAULT_TEXT); // MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("inputDocument", fileBody); builder.addPart("outputFormat", stringBody1); HttpEntity entity = builder.build(); // post.setEntity(entity); CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response1 = client.execute(post); //Object[] response = null; try { HttpEntity entity1 = response1.getEntity(); //String responseBody = responseAsString(response1); int responseStatus = response1.getStatusLine().getStatusCode(); System.out.println("responseStatus: " + responseStatus); //response = new Object [] {responseStatus, responseBody}; // do something useful with the response body // and ensure it is fully consumed //EntityUtils.consume(entity1); //int length = (int) entity1.getContentLength(); System.out.println("length: " + entity1.getContentLength()); System.out.println("ctype: " + entity1.getContentType()); /* if (entity1 != null) { String respoBody = EntityUtils.toString(entity1, "UTF-8"); System.out.println(respoBody); } */ } finally { response1.close(); } client.close(); }
Example 18
Source File: RestJodConverterStressTest.java From document-management-software with GNU Lesser General Public License v3.0 | 4 votes |
public static void addBinaryBody03(File documentFile) throws Exception { //System.out.println("createDocument(CloseableHttpClient)"); CloseableHttpClient httpclient = HttpClients.createDefault(); //HttpPost httppost = new HttpPost("http://localhost:8080/jodapp/converted/document.pdf"); HttpPost httppost = new HttpPost("http://localhost:8080/jodxwiki/converted/document.pdf"); //HttpPost httppost = new HttpPost("http://ubuntu14:8080/jodapp/converted/document.pdf"); //HttpPost httppost = new HttpPost("http://ubuntu14:8080/jodxwiki/converted/document.pdf"); //File f = new File("C:/tmp/AnalisiTraffico.xlsx"); File f = documentFile; System.out.println(f.getName()); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // The one commented below is to run correctly on Windows 10 Professional 64bit builder.addBinaryBody("inputDocument", f, ContentType.DEFAULT_BINARY, f.getName()).setCharset(Charset.forName("UTF-8")); //builder.addBinaryBody("inputDocument", f, ContentType.DEFAULT_BINARY, f.getName()); // Unix - Linux builder.addTextBody("outputFormat", "pdf", ContentType.DEFAULT_BINARY); // HttpEntity reqEntity = builder.build(); httppost.setEntity(reqEntity); CloseableHttpResponse response = httpclient.execute(httppost); try { int responseStatus = response.getStatusLine().getStatusCode(); System.out.println("responseStatus: " + responseStatus); HttpEntity rent = response.getEntity(); if (rent != null) { /*String respoBody = EntityUtils.toString(rent, "UTF-8"); System.out.println(respoBody); */ System.out.println("ctype: " + rent.getContentType()); System.out.println("length: " + rent.getContentLength()); if (responseStatus == 200) { // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(rent); /* String baseName = FilenameUtils.getBaseName(documentFile.getName()); File outputFile = new File(outputFolder, baseName + ".pdf"); OutputStream outputStream = null; InputStream inputStream = null; try { outputStream = new FileOutputStream(outputFile); inputStream = rent.getContent(); IOUtils.copy(inputStream, outputStream); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } */ } else { String respoBody = EntityUtils.toString(rent, "UTF-8"); System.err.println("responseStatus: " + responseStatus); System.err.println(f.getName()); System.err.println(respoBody); errors++; } } } finally { response.close(); } }
Example 19
Source File: RestJodConverterStressTest.java From document-management-software with GNU Lesser General Public License v3.0 | 4 votes |
public static void addPartMethod01(File documentFile) throws Exception { //String textFileName = "C:/tmp/AnalisiTraffico.xlsx"; //File file = new File(textFileName); File file = documentFile; //HttpPost post = new HttpPost("http://localhost:8080/jodapp/"); ///jodapp/converted/document.pdf HttpPost httppost = new HttpPost("http://localhost:8080/jodapp/converted/document.pdf"); FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); StringBody stringBody1 = new StringBody("pdf", ContentType.DEFAULT_TEXT); // MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("inputDocument", fileBody); builder.addPart("outputFormat", stringBody1); HttpEntity entity = builder.build(); // httppost.setEntity(entity); CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = httpclient.execute(httppost); try { int responseStatus = response.getStatusLine().getStatusCode(); System.out.println("responseStatus: " + responseStatus); HttpEntity rent = response.getEntity(); if (rent != null) { /*String respoBody = EntityUtils.toString(rent, "UTF-8"); System.out.println(respoBody); */ System.out.println("ctype: " + rent.getContentType()); System.out.println("length: " + rent.getContentLength()); if (responseStatus == 200) { // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(rent); } else { String respoBody = EntityUtils.toString(rent, "UTF-8"); System.err.println("responseStatus: " + responseStatus); System.err.println(file.getName()); System.err.println(respoBody); } } } finally { response.close(); } httpclient.close(); }
Example 20
Source File: MessageTools.java From xiaoV with GNU General Public License v3.0 | 4 votes |
/** * 上传多媒体文件到 微信服务器,目前应该支持3种类型: 1. pic 直接显示,包含图片,表情 2.video 3.doc 显示为文件,包含PDF等 * * @param filePath * @return * @author https://github.com/yaphone * @date 2017年5月7日 上午12:41:13 */ private static JSONObject webWxUploadMedia(String filePath) { File f = new File(filePath); if (!f.exists() && f.isFile()) { LOG.info("file is not exist"); return null; } String url = String.format(URLEnum.WEB_WX_UPLOAD_MEDIA.getUrl(), core .getLoginInfo().get("fileUrl")); String mimeType = new MimetypesFileTypeMap().getContentType(f); String mediaType = ""; if (mimeType == null) { mimeType = "text/plain"; } else { mediaType = mimeType.split("/")[0].equals("image") ? "pic" : "doc"; } String lastModifieDate = new SimpleDateFormat("yyyy MM dd HH:mm:ss") .format(new Date()); long fileSize = f.length(); String passTicket = (String) core.getLoginInfo().get("pass_ticket"); String clientMediaId = String.valueOf(new Date().getTime()) + String.valueOf(new Random().nextLong()).substring(0, 4); String webwxDataTicket = MyHttpClient.getCookie("webwx_data_ticket"); if (webwxDataTicket == null) { LOG.error("get cookie webwx_data_ticket error"); return null; } Map<String, Object> paramMap = core.getParamMap(); paramMap.put("ClientMediaId", clientMediaId); paramMap.put("TotalLen", fileSize); paramMap.put("StartPos", 0); paramMap.put("DataLen", fileSize); paramMap.put("MediaType", 4); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addTextBody("id", "WU_FILE_0", ContentType.TEXT_PLAIN); builder.addTextBody("name", filePath, ContentType.TEXT_PLAIN); builder.addTextBody("type", mimeType, ContentType.TEXT_PLAIN); builder.addTextBody("lastModifieDate", lastModifieDate, ContentType.TEXT_PLAIN); builder.addTextBody("size", String.valueOf(fileSize), ContentType.TEXT_PLAIN); builder.addTextBody("mediatype", mediaType, ContentType.TEXT_PLAIN); builder.addTextBody("uploadmediarequest", JSON.toJSONString(paramMap), ContentType.TEXT_PLAIN); builder.addTextBody("webwx_data_ticket", webwxDataTicket, ContentType.TEXT_PLAIN); builder.addTextBody("pass_ticket", passTicket, ContentType.TEXT_PLAIN); builder.addBinaryBody("filename", f, ContentType.create(mimeType), filePath); HttpEntity reqEntity = builder.build(); HttpEntity entity = myHttpClient.doPostFile(url, reqEntity); if (entity != null) { try { String result = EntityUtils.toString(entity, Consts.UTF_8); return JSON.parseObject(result); } catch (Exception e) { LOG.error("webWxUploadMedia 错误: ", e); } } return null; }