List of usage examples for org.apache.http.entity.mime.content ByteArrayBody ByteArrayBody
public ByteArrayBody(final byte[] data, final String mimeType, final String filename)
From source file:org.droidparts.net.http.worker.wrapper.HttpMimeWrapper.java
public static HttpEntity buildMultipartEntity(String name, String contentType, String fileName, InputStream is) throws IOException { byte[] data = IOUtils.readToByteArray(is); ContentBody contentBody;//w w w .j av a 2 s . c o m if (contentType != null) { contentBody = new ByteArrayBody(data, contentType, fileName); } else { contentBody = new ByteArrayBody(data, fileName); } MultipartEntity entity = new MultipartEntity(); entity.addPart(name, contentBody); return entity; }
From source file:com.ls.http.base.handler.multipart.ByteMultipartEntityPart.java
@Override public ContentBody getContentBody() { return new ByteArrayBody(value, mimeType, fileName); }
From source file:org.jboss.test.capedwarf.blobstore.support.FileUploader.java
public String uploadFile(String uri, String partName, String filename, String mimeType, byte[] contents) throws URISyntaxException, IOException { HttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost(uri); MultipartEntity entity = new MultipartEntity(); ByteArrayBody contentBody = new ByteArrayBody(contents, mimeType, filename); entity.addPart(partName, contentBody); post.setEntity(entity);/*from www . j a va 2s . c om*/ HttpResponse response = httpClient.execute(post); return EntityUtils.toString(response.getEntity()); }
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;// w w w. j a v a 2 s. c om 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:org.opendatakit.aggregate.format.element.OhmageJsonElementFormatter.java
@Override public void formatBinary(BlobSubmissionType blobSubmission, FormElementModel element, String ordinalValue, Row row, CallingContext cc) throws ODKDatastoreException { if (!(blobSubmission == null || (blobSubmission.getAttachmentCount(cc) == 0) || (blobSubmission.getContentHash(1, cc) == null))) { byte[] imageBlob = null; if (blobSubmission.getAttachmentCount(cc) == 1) { imageBlob = blobSubmission.getBlob(1, cc); }/* w w w. ja va 2s . c o m*/ if (imageBlob != null && imageBlob.length > 0) { UUID photoUUID = UUID.randomUUID(); OhmageJsonTypes.photo photo = new OhmageJsonTypes.photo(element.getElementName(), photoUUID); responses.add(photo); photos.put(photoUUID, new ByteArrayBody(imageBlob, blobSubmission.getContentType(1, cc), photoUUID.toString())); } } }
From source file:org.cmuchimps.gort.modules.webinfoservice.AppEngineUpload.java
private static String uploadBlobstoreDataNoRetry(String url, String filename, String mime, byte[] data) { if (url == null || url.length() <= 0) { return null; }//from ww w .j a va 2 s .com if (data == null || data.length <= 0) { return null; } HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("data", new ByteArrayBody(data, mime, filename)); httpPost.setEntity(entity); try { HttpResponse response = httpClient.execute(httpPost); System.out.println("Blob upload status code: " + response.getStatusLine().getStatusCode()); /* //http://grinder.sourceforge.net/g3/script-javadoc/HTTPClient/HTTPResponse.html // 2xx - success if (response.getStatusLine().getStatusCode() / 100 != 2) { return null; } */ InputStreamReader isr = new InputStreamReader(response.getEntity().getContent()); BufferedReader br = new BufferedReader(isr); String blobKey = br.readLine(); blobKey = (blobKey != null) ? blobKey.trim() : null; br.close(); isr.close(); if (blobKey != null && blobKey.length() > 0) { return String.format("%s%s", MTURKSERVER_BLOB_DOWNLOAD_URL, blobKey); } else { return null; } } catch (ClientProtocolException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } }
From source file:edu.uah.itsc.aws.RubyClient.java
public void postFile(byte[] image) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); // HttpPost httppost = new // HttpPost("http://ec2-107-21-179-173.compute-1.amazonaws.com:3000/posts"); HttpPost httppost = new HttpPost(publicURL); ContentBody cb = new ByteArrayBody(image, "text/plain; charset=utf8", fname); // ContentBody cb = new InputStreamBody(new ByteArrayInputStream(image), // "image/jpg", "icon.jpg"); MultipartEntity mpentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); // mpentity.addPart(cb.); // mpentity.addPart("utf8", new // StringBody((Character.toString('\u2713')))); mpentity.addPart("post[photo]", cb); mpentity.addPart("post[content]", new StringBody(desc)); // mpentity.addPart("post[filename]", new StringBody( fname)); mpentity.addPart("post[title]", new StringBody(title)); mpentity.addPart("post[bucket]", new StringBody(bucket)); mpentity.addPart("post[user]", new StringBody(User.username)); mpentity.addPart("post[folder]", new StringBody(folder)); mpentity.addPart("commit", new StringBody("Create Post")); httppost.setEntity(mpentity);//from ww w. j av a 2s . com String response = EntityUtils.toString(httpclient.execute(httppost).getEntity(), "UTF-8"); System.out.println(response); }
From source file:org.uberfire.provisioning.wildfly.runtime.provider.extras.Wildfly10RemoteClient.java
public int deploy(String user, String password, String host, int port, String filePath) { // the digest auth backend CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(user, password)); CloseableHttpClient httpclient = custom().setDefaultCredentialsProvider(credsProvider).build(); HttpPost post = new HttpPost("http://" + host + ":" + port + "/management-upload"); post.addHeader("X-Management-Client-Name", "HAL"); // the file to be uploaded File file = new File(filePath); FileBody fileBody = new FileBody(file); // the DMR operation ModelNode operation = new ModelNode(); operation.get("address").add("deployment", file.getName()); operation.get("operation").set("add"); operation.get("runtime-name").set(file.getName()); operation.get("enabled").set(true); operation.get("content").add().get("input-stream-index").set(0); // point to the multipart index used ByteArrayOutputStream bout = new ByteArrayOutputStream(); try {/*ww w . j a v a2 s . c o m*/ operation.writeBase64(bout); } catch (IOException ex) { getLogger(Wildfly10RemoteClient.class.getName()).log(SEVERE, null, ex); } // the multipart MultipartEntityBuilder builder = create(); builder.setMode(BROWSER_COMPATIBLE); builder.addPart("uploadFormElement", fileBody); builder.addPart("operation", new ByteArrayBody(bout.toByteArray(), create("application/dmr-encoded"), "blob")); HttpEntity entity = builder.build(); //entity.writeTo(System.out); post.setEntity(entity); try { HttpResponse response = httpclient.execute(post); out.println(">>> Deploying Response Entity: " + response.getEntity()); out.println(">>> Deploying Response Satus: " + response.getStatusLine().getStatusCode()); return response.getStatusLine().getStatusCode(); } catch (IOException ex) { ex.printStackTrace(); getLogger(Wildfly10RemoteClient.class.getName()).log(SEVERE, null, ex); } return -1; }
From source file:com.google.appengine.tck.blobstore.support.FileUploader.java
public String uploadFile(String uri, String partName, String filename, String mimeType, byte[] contents, int expectedResponseCode) throws URISyntaxException, IOException { HttpClient httpClient = new DefaultHttpClient(); try {//from w w w. j av a2s. c o m HttpPost post = new HttpPost(uri); MultipartEntity entity = new MultipartEntity(); ByteArrayBody contentBody = new ByteArrayBody(contents, mimeType, filename); entity.addPart(partName, contentBody); post.setEntity(entity); HttpResponse response = httpClient.execute(post); String result = EntityUtils.toString(response.getEntity()); int statusCode = response.getStatusLine().getStatusCode(); Assert.assertEquals(String.format("Invalid response code, %s", statusCode), expectedResponseCode, statusCode); return result; } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:org.retrostore.data.BlobstoreWrapperImpl.java
@Override public void addScreenshot(String appId, byte[] data, Responder.ContentType contentType, String cookie) { Preconditions.checkArgument(!Strings.isNullOrEmpty(appId), "'appId' missing"); Preconditions.checkArgument(data != null && data.length > 0, "'data' is empty"); Preconditions.checkNotNull(contentType, "'contentType' missing"); Preconditions.checkArgument(!Strings.isNullOrEmpty(cookie), "'cookie' missing"); LOG.info(String.format("About to add a screenshot blob of size %d with type %s.", data.length, contentType.str));// w w w. j a v a2 s .c o m final String PATH_UPLOAD = "/screenshotUpload"; String forwardTo = PATH_UPLOAD + "?appId=" + appId; LOG.info("Forward to: " + forwardTo); String uploadUrl = createUploadUrl(forwardTo); LOG.info("UploadUrl: " + uploadUrl); // It is important that we set the cookie so that we're authenticated. We do not allow // anonymous requests to upload screenshots. HttpPost post = new HttpPost(uploadUrl); post.setHeader("Cookie", cookie); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // Note we need to use the deprecated constructor so we can use our content type. builder.addPart("file", new ByteArrayBody(data, contentType.str, "screenshot")); HttpEntity entity = builder.build(); post.setEntity(entity); HttpClient client = HttpClientBuilder.create().build(); try { LOG.info("POST constructed. About to make request!"); HttpResponse response = client.execute(post); LOG.info("Request succeeded!"); ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); LOG.info(new String(out.toByteArray(), "UTF-8")); } catch (IOException e) { LOG.log(Level.SEVERE, "Cannot make POST request.", e); } }