List of usage examples for org.apache.http.entity.mime.content StringBody StringBody
public StringBody(final String text, Charset charset) throws UnsupportedEncodingException
From source file:ch.ralscha.extdirectspring_itest.FileUploadServiceTest.java
@Test public void testUpload() throws IOException { CloseableHttpClient client = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try {//www.ja v a 2s .c om HttpPost post = new HttpPost("http://localhost:9998/controller/router"); InputStream is = getClass().getResourceAsStream("/UploadTestFile.txt"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); ContentBody cbFile = new InputStreamBody(is, ContentType.create("text/plain"), "UploadTestFile.txt"); builder.addPart("fileUpload", cbFile); builder.addPart("extTID", new StringBody("2", ContentType.DEFAULT_TEXT)); builder.addPart("extAction", new StringBody("fileUploadService", ContentType.DEFAULT_TEXT)); builder.addPart("extMethod", new StringBody("uploadTest", ContentType.DEFAULT_TEXT)); builder.addPart("extType", new StringBody("rpc", ContentType.DEFAULT_TEXT)); builder.addPart("extUpload", new StringBody("true", ContentType.DEFAULT_TEXT)); builder.addPart("name", new StringBody("Jim", ContentType.create("text/plain", Charset.forName("UTF-8")))); builder.addPart("firstName", new StringBody("Ralph", ContentType.DEFAULT_TEXT)); builder.addPart("age", new StringBody("25", ContentType.DEFAULT_TEXT)); builder.addPart("email", new StringBody("test@test.ch", ContentType.DEFAULT_TEXT)); post.setEntity(builder.build()); response = client.execute(post); HttpEntity resEntity = response.getEntity(); assertThat(resEntity).isNotNull(); String responseString = EntityUtils.toString(resEntity); String prefix = "<html><body><textarea>"; String postfix = "</textarea></body></html>"; assertThat(responseString).startsWith(prefix); assertThat(responseString).endsWith(postfix); String json = responseString.substring(prefix.length(), responseString.length() - postfix.length()); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> rootAsMap = mapper.readValue(json, Map.class); assertThat(rootAsMap).hasSize(5); assertThat(rootAsMap.get("method")).isEqualTo("uploadTest"); assertThat(rootAsMap.get("type")).isEqualTo("rpc"); assertThat(rootAsMap.get("action")).isEqualTo("fileUploadService"); assertThat(rootAsMap.get("tid")).isEqualTo(2); @SuppressWarnings("unchecked") Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result"); assertThat(result).hasSize(7); assertThat(result.get("name")).isEqualTo("Jim"); assertThat(result.get("firstName")).isEqualTo("Ralph"); assertThat(result.get("age")).isEqualTo(25); assertThat(result.get("e-mail")).isEqualTo("test@test.ch"); assertThat(result.get("fileName")).isEqualTo("UploadTestFile.txt"); assertThat(result.get("fileContents")).isEqualTo("contents of upload file"); assertThat(result.get("success")).isEqualTo(Boolean.TRUE); EntityUtils.consume(resEntity); is.close(); } finally { IOUtils.closeQuietly(response); IOUtils.closeQuietly(client); } }
From source file:ch.ralscha.extdirectspring_itest.FileUploadControllerTest.java
@Test public void testUpload() throws IOException { CloseableHttpClient client = HttpClientBuilder.create().build(); InputStream is = null;/*w ww.java2 s. c o m*/ CloseableHttpResponse response = null; try { HttpPost post = new HttpPost("http://localhost:9998/controller/router"); is = getClass().getResourceAsStream("/UploadTestFile.txt"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); ContentBody cbFile = new InputStreamBody(is, ContentType.create("text/plain"), "UploadTestFile.txt"); builder.addPart("fileUpload", cbFile); builder.addPart("extTID", new StringBody("2", ContentType.DEFAULT_TEXT)); builder.addPart("extAction", new StringBody("fileUploadController", ContentType.DEFAULT_TEXT)); builder.addPart("extMethod", new StringBody("uploadTest", ContentType.DEFAULT_TEXT)); builder.addPart("extType", new StringBody("rpc", ContentType.DEFAULT_TEXT)); builder.addPart("extUpload", new StringBody("true", ContentType.DEFAULT_TEXT)); builder.addPart("name", new StringBody("Jim", ContentType.create("text/plain", Charset.forName("UTF-8")))); builder.addPart("firstName", new StringBody("Ralph", ContentType.DEFAULT_TEXT)); builder.addPart("age", new StringBody("25", ContentType.DEFAULT_TEXT)); builder.addPart("email", new StringBody("test@test.ch", ContentType.DEFAULT_TEXT)); post.setEntity(builder.build()); response = client.execute(post); HttpEntity resEntity = response.getEntity(); assertThat(resEntity).isNotNull(); String responseString = EntityUtils.toString(resEntity); String prefix = "<html><body><textarea>"; String postfix = "</textarea></body></html>"; assertThat(responseString).startsWith(prefix); assertThat(responseString).endsWith(postfix); String json = responseString.substring(prefix.length(), responseString.length() - postfix.length()); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> rootAsMap = mapper.readValue(json, Map.class); assertThat(rootAsMap).hasSize(5); assertThat(rootAsMap.get("method")).isEqualTo("uploadTest"); assertThat(rootAsMap.get("type")).isEqualTo("rpc"); assertThat(rootAsMap.get("action")).isEqualTo("fileUploadController"); assertThat(rootAsMap.get("tid")).isEqualTo(2); @SuppressWarnings("unchecked") Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result"); assertThat(result).hasSize(7); assertThat(result.get("name")).isEqualTo("Jim"); assertThat(result.get("firstName")).isEqualTo("Ralph"); assertThat(result.get("age")).isEqualTo(25); assertThat(result.get("email")).isEqualTo("test@test.ch"); assertThat(result.get("fileName")).isEqualTo("UploadTestFile.txt"); assertThat(result.get("fileContents")).isEqualTo("contents of upload file"); assertThat(result.get("success")).isEqualTo(Boolean.TRUE); EntityUtils.consume(resEntity); } finally { IOUtils.closeQuietly(response); IOUtils.closeQuietly(is); IOUtils.closeQuietly(client); } }
From source file:com.openkm.applet.Util.java
/** * Upload scanned document to OpenKM/*from ww w .j a v a 2 s .co m*/ * */ public static String createDocument(String token, String path, String fileName, String fileType, String url, List<BufferedImage> images) throws MalformedURLException, IOException { log.info("createDocument(" + token + ", " + path + ", " + fileName + ", " + fileType + ", " + url + ", " + images + ")"); File tmpDir = createTempDir(); File tmpFile = new File(tmpDir, fileName + "." + fileType); ImageOutputStream ios = ImageIO.createImageOutputStream(tmpFile); String response = ""; try { if ("pdf".equals(fileType)) { ImageUtils.writePdf(images, ios); } else if ("tif".equals(fileType)) { ImageUtils.writeTiff(images, ios); } else { if (!ImageIO.write(images.get(0), fileType, ios)) { throw new IOException("Not appropiated writer found!"); } } ios.flush(); ios.close(); if (token != null) { // Send image HttpClient client = new DefaultHttpClient(); MultipartEntity form = new MultipartEntity(); form.addPart("file", new FileBody(tmpFile)); form.addPart("path", new StringBody(path, Charset.forName("UTF-8"))); form.addPart("action", new StringBody("0")); // FancyFileUpload.ACTION_INSERT HttpPost post = new HttpPost(url + "/frontend/FileUpload;jsessionid=" + token); post.setHeader("Cookie", "jsessionid=" + token); post.setEntity(form); ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(post, responseHandler); } else { // Store in disk String home = System.getProperty("user.home"); File dst = new File(home, tmpFile.getName()); copyFile(tmpFile, dst); response = "Image copied to " + dst.getPath(); } } finally { FileUtils.deleteQuietly(tmpDir); } log.info("createDocument: " + response); return response; }
From source file:org.wso2.ml.client.MLClient.java
public CloseableHttpResponse createdDataSet(JSONObject datasetConf) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(mlHost + "/api/datasets/"); httpPost.setHeader(MLConstants.AUTHORIZATION_HEADER, getBasicAuthKey()); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addPart("description", new StringBody(datasetConf.get("description").toString(), ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("sourceType", new StringBody(datasetConf.get("sourceType").toString(), ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("destination", new StringBody(datasetConf.get("destination").toString(), ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("dataFormat", new StringBody(datasetConf.get("dataFormat").toString(), ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("containsHeader", new StringBody(datasetConf.get("containsHeader").toString(), ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("datasetName", new StringBody(datasetConf.get("datasetName").toString(), ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("version", new StringBody(datasetConf.get("version").toString(), ContentType.TEXT_PLAIN)); File file = new File(mlDatasetPath); multipartEntityBuilder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, datasetConf.get("file").toString()); httpPost.setEntity(multipartEntityBuilder.build()); return httpClient.execute(httpPost); }
From source file:org.knoxcraft.http.client.ClientMultipartFormPost.java
public static void upload(String url, String playerName, File jsonfile, File sourcefile) throws ClientProtocolException, IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); try {// w w w .j av a2 s . co m HttpPost httppost = new HttpPost(url); FileBody json = new FileBody(jsonfile); FileBody source = new FileBody(sourcefile); String jsontext = readFromFile(jsonfile); HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("playerName", new StringBody(playerName, ContentType.TEXT_PLAIN)) .addPart("jsonfile", json).addPart("sourcefile", source) .addPart("language", new StringBody("java", ContentType.TEXT_PLAIN)) .addPart("jsontext", new StringBody(jsontext, ContentType.TEXT_PLAIN)).addPart("sourcetext", new StringBody("public class Foo {\n int x=5\n}", ContentType.TEXT_PLAIN)) .build(); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { //System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { //System.out.println("Response content length: " + resEntity.getContentLength()); Scanner sc = new Scanner(resEntity.getContent()); while (sc.hasNext()) { System.out.println(sc.nextLine()); } sc.close(); EntityUtils.consume(resEntity); } } finally { response.close(); } } finally { httpclient.close(); } }
From source file:net.yacy.cora.document.encoding.UTF8.java
public final static StringBody StringBody(final String s) { return new StringBody(s == null ? "" : s, contentType); }
From source file:org.dataconservancy.ui.it.support.IngestPackageRequest.java
public HttpPost asHttpPost(String packageMimeType) throws UnsupportedEncodingException { if (packageToIngest == null) { throw new IllegalStateException( "The package to ingest must not be null: call setPackageToIngest(File) " + "first"); }//from w ww . j a v a 2 s. co m final HttpPost request = new HttpPost(urlConfig.getIngestPackageUrl().toString()); // // // if (packageMimeType != null) { // request.setHeader(HttpHeaders.CONTENT_TYPE, packageMimeType); // } // // request.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(packageToIngest.length())); final MultipartEntity multiPart = new MultipartEntity(); final FileBody fileBody; if (packageMimeType != null) { fileBody = new FileBody(packageToIngest, packageMimeType); } else { fileBody = new FileBody(packageToIngest); } multiPart.addPart("uploadedFile", fileBody); multiPart.addPart(INGEST_STRIPES_EVENT, new StringBody("Ingest", Charset.forName("UTF-8"))); request.setEntity(multiPart); return request; }
From source file:org.dataconservancy.ui.it.support.ValidatingMetadataFileRequest.java
public HttpPost asHttpPost() { if (fileToTest == null) { throw new IllegalStateException("File not set: call setFileToTest(File) first"); }//from w w w.j ava 2 s. c o m String validatingMetadataFileUrl = urlConfig.getAdminValidatingMetadataFilePathPostUrl().toString(); HttpPost post = new HttpPost(validatingMetadataFileUrl); MultipartEntity entity = new MultipartEntity(); try { entity.addPart(STRIPES_EVENT, new StringBody("Validate", Charset.forName("UTF-8"))); entity.addPart("metadataFormatId", new StringBody(formatId, Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } FileBody fileBody = new FileBody(fileToTest); entity.addPart("sampleMetadataFile", fileBody); post.setEntity(entity); return post; }
From source file:com.wattzap.model.social.SelfLoopsAPI.java
public static int uploadActivity(String email, String passWord, String fileName, String note) throws IOException { JSONObject jsonObj = null;//from www . j a v a 2s. com FileInputStream in = null; GZIPOutputStream out = null; CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(url); httpPost.setHeader("enctype", "multipart/mixed"); in = new FileInputStream(fileName); // Create stream to compress data and write it to the to file. ByteArrayOutputStream obj = new ByteArrayOutputStream(); out = new GZIPOutputStream(obj); // Copy bytes from one stream to the other byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) { out.write(buffer, 0, bytes_read); } out.close(); in.close(); ByteArrayBody bin = new ByteArrayBody(obj.toByteArray(), ContentType.create("application/x-gzip"), fileName); HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("email", new StringBody(email, ContentType.TEXT_PLAIN)) .addPart("pw", new StringBody(passWord, ContentType.TEXT_PLAIN)).addPart("tcxfile", bin) .addPart("note", new StringBody(note, ContentType.TEXT_PLAIN)).build(); httpPost.setEntity(reqEntity); CloseableHttpResponse response = null; try { response = httpClient.execute(httpPost); int code = response.getStatusLine().getStatusCode(); switch (code) { case 200: HttpEntity respEntity = response.getEntity(); if (respEntity != null) { // EntityUtils to get the response content String content = EntityUtils.toString(respEntity); //System.out.println(content); JSONParser jsonParser = new JSONParser(); jsonObj = (JSONObject) jsonParser.parse(content); } break; case 403: throw new RuntimeException( "Authentification failure " + email + " " + response.getStatusLine()); default: throw new RuntimeException("Error " + code + " " + response.getStatusLine()); } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (response != null) { response.close(); } } int activityId = ((Long) jsonObj.get("activity_id")).intValue(); // parse error code int error = ((Long) jsonObj.get("error_code")).intValue(); if (activityId == -1) { String message = (String) jsonObj.get("message"); switch (error) { case 102: throw new RuntimeException("Empty TCX file " + fileName); case 103: throw new RuntimeException("Invalide TCX Format " + fileName); case 104: throw new RuntimeException("TCX Already Present " + fileName); case 105: throw new RuntimeException("Invalid XML " + fileName); case 106: throw new RuntimeException("invalid compression algorithm"); case 107: throw new RuntimeException("Invalid file mime types"); default: throw new RuntimeException(message + " " + error); } } return activityId; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } httpClient.close(); } }
From source file:com.mashape.unirest.request.body.MultipartBody.java
public HttpEntity getEntity() { if (hasFile) { MultipartEntity entity = new MultipartEntity(); for (Entry<String, Object> part : parameters.entrySet()) { if (part.getValue() instanceof File) { hasFile = true;//ww w. j av a2 s . c o m entity.addPart(part.getKey(), new FileBody((File) part.getValue())); } else { try { entity.addPart(part.getKey(), new StringBody(part.getValue().toString(), Charset.forName(UTF_8))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } return entity; } else { try { return new UrlEncodedFormEntity(MapUtil.getList(parameters), UTF_8); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } }