Example usage for org.apache.http.entity.mime.content ByteArrayBody ByteArrayBody

List of usage examples for org.apache.http.entity.mime.content ByteArrayBody ByteArrayBody

Introduction

In this page you can find the example usage for org.apache.http.entity.mime.content ByteArrayBody ByteArrayBody.

Prototype

public ByteArrayBody(final byte[] data, final String filename) 

Source Link

Document

Creates a new ByteArrayBody.

Usage

From source file:outfox.dict.contest.util.FileUtils.java

/**
 * ?NOSurl/*from   www .  j av a  2  s  .  co m*/
 * tongkn
 * @param bytes
 * @return
 */
public static String uploadFile2Nos(byte[] bytes, String fileName) throws Exception {
    if (bytes == null) {
        return null;
    }
    HttpResponse response = null;
    String result = null;
    try {
        //web ??
        String filedir = "tmpfile";
        File dir = new File(filedir);
        if (!dir.exists()) {
            dir.mkdir();
        }
        //            FileBody bin = new FileBody(FileUtils.getFileFromBytes(
        //                    bytes, filedir +"/file-"+ System.currentTimeMillis()+"-"+fileName));
        //ByteArrayBody
        ByteArrayBody bin = new ByteArrayBody(bytes, fileName);
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("file", bin);
        reqEntity.addPart("video", new StringBody("false", Charset.forName("UTF-8")));
        //            reqEntity.addPart("contentType", new StringBody("audio/mpeg", Charset.forName("UTF-8")));
        response = HttpToolKit.getInstance().doPost(ContestConsts.NOS_UPLOAD_Interface, reqEntity);
        if (response != null) {
            String jsonString = EntityUtils.toString(response.getEntity());
            JSONObject json = JSON.parseObject(jsonString);
            if ("success".equals(json.getString("msg"))) {
                return json.getString("url");
            }
        }
    } catch (Exception e) {
        LOG.error("FileUtils.uploadFile2Nos(bytes) error...", e);
        throw new Exception();
    } finally {
        HttpToolKit.closeQuiet(response);
    }
    return result;
}

From source file:com.jigarmjoshi.service.task.UploaderTask.java

private final boolean uploadEntryReport(Report entry) {
    if (entry == null || entry.getUploaded()) {
        return true;
    }/*from ww w  .j  a v  a 2s  .c o m*/
    boolean resultFlag = false;
    try {
        Log.i(UploaderTask.class.getSimpleName(), "uploading " + entry.getImageFileName());
        Bitmap bm = BitmapFactory.decodeFile(entry.getImageFileName());
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bm.compress(CompressFormat.JPEG, 60, bos);
        byte[] data = bos.toByteArray();
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(this.serverUrl + "/uploadEntryRecord");
        ByteArrayBody bab = new ByteArrayBody(data, "report.jpg");
        // File file= new File("/mnt/sdcard/forest.png");
        // FileBody bin = new FileBody(file);
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        reqEntity.addPart("lat", new StringBody(Utility.encode(entry.getLat())));
        reqEntity.addPart("lon", new StringBody(Utility.encode(entry.getLon())));
        reqEntity.addPart("priority", new StringBody(Utility.encode(entry.getPriority())));
        reqEntity.addPart("fileName", new StringBody(Utility.encode(entry.getImageFileName())));
        reqEntity.addPart("reporterId", new StringBody(Utility.encode(entry.getId())));
        reqEntity.addPart("uploaded", bab);
        postRequest.setEntity(reqEntity);
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String sResponse;
        StringBuilder responseString = new StringBuilder();

        while ((sResponse = reader.readLine()) != null) {
            responseString = responseString.append(sResponse);
        }
        Log.i(UploaderTask.class.getSimpleName(), responseString.toString());
        if ("SUCCESS".equalsIgnoreCase(responseString.toString())) {
            resultFlag = true;
            if (entry.getImageFileName() != null) {
                File imageFileToDelete = new File(entry.getImageFileName());
                boolean deleted = imageFileToDelete.delete();

                if (deleted) {
                    Log.i(UploaderTask.class.getSimpleName(), "deleted = ?" + deleted);
                    MediaScannerConnection.scanFile(context, new String[] {

                            imageFileToDelete.getAbsolutePath() },

                            null, new MediaScannerConnection.OnScanCompletedListener() {

                                public void onScanCompleted(String path, Uri uri)

                            {

                                }

                            });

                }
            }
        }

    } catch (Exception ex) {
        Log.e(UploaderTask.class.getSimpleName(), "failed to upload", ex);
        resultFlag = false;
    }
    return resultFlag;
}

From source file:de.hska.ld.content.controller.DocumentControllerIntegrationTest.java

@Test
public void testFileUpload() throws Exception {
    //Add document
    HttpResponse responseCreateDocument = UserSession.user().post(RESOURCE_DOCUMENT, document);
    Document respondedDocument = ResponseHelper.getBody(responseCreateDocument, Document.class);
    Assert.assertNotNull(respondedDocument);

    //load file//ww  w .ja v  a2  s .  c  o m
    String fileName = "sandbox.pdf";
    InputStream in = null;
    byte[] source = null;
    try {
        in = UserSession.class.getResourceAsStream("/" + fileName);
        source = IOUtils.toByteArray(in);
    } finally {
        IOUtils.closeQuietly(in);
    }
    ByteArrayBody fileBody = new ByteArrayBody(source, fileName);

    //Add document
    System.out.println(RESOURCE_DOCUMENT + "/upload?documentId=" + respondedDocument.getId());
    HttpResponse responseUploadAttachment = UserSession.user()
            .postFile(RESOURCE_DOCUMENT + "/upload?documentId=" + respondedDocument.getId(), fileBody);
    Assert.assertEquals(HttpStatus.OK, ResponseHelper.getStatusCode(responseUploadAttachment));
    Long attachmentId = ResponseHelper.getBody(responseUploadAttachment, Long.class);
    Assert.assertNotNull(attachmentId);
}

From source file:com.grouzen.android.serenity.HttpConnection.java

private HttpResponse post(String url, Bundle params) throws ClientProtocolException, IOException {
    HttpPost method = new HttpPost(url);

    if (params != null) {
        try {//from  www. j  a v  a 2s  . c  o m
            if (mMultipartKey != null && mMultipartFileName != null) {
                ByteArrayBody byteArrayBody = new ByteArrayBody(params.getByteArray(mMultipartKey),
                        mMultipartFileName);
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                Charset charset = Charset.forName(CHARSET);

                entity.addPart(mMultipartKey, byteArrayBody);
                params.remove(mMultipartKey);

                for (String k : params.keySet()) {
                    entity.addPart(new FormBodyPart(k, new StringBody(params.getString(k), charset)));
                }

                method.setEntity(entity);
            } else {
                ArrayList<NameValuePair> entity = convertParams(params);

                method.setEntity(new UrlEncodedFormEntity(entity, CHARSET));

            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    return execute(method);
}

From source file:io.undertow.servlet.test.security.basic.ServletCertAndDigestAuthTestCase.java

@Test
public void testMultipartRequest() throws Exception {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 2000; i++) {
        sb.append("0123456789");
    }/*from w  ww  .j  a  va2s  .  co  m*/

    try (TestHttpClient client = new TestHttpClient()) {
        // create POST request
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addPart("part1", new ByteArrayBody(sb.toString().getBytes(), "file.txt"));
        builder.addPart("part2", new StringBody("0123456789", ContentType.TEXT_HTML));
        HttpEntity entity = builder.build();

        client.setSSLContext(clientSSLContext);
        String url = DefaultServer.getDefaultServerSSLAddress() + BASE_PATH + "multipart";
        HttpPost post = new HttpPost(url);
        post.setEntity(entity);
        post.addHeader(AUTHORIZATION.toString(), BASIC + " " + FlexBase64
                .encodeString(("user1" + ":" + "password1").getBytes(StandardCharsets.UTF_8), false));

        HttpResponse result = client.execute(post);
        assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
    }
}

From source file:de.hska.ld.content.controller.DocumentControllerIntegrationTest.java

@Test
public void testFileDownload() throws Exception {

    //Add document
    HttpResponse responseCreateDocument = UserSession.user().post(RESOURCE_DOCUMENT, document);
    Document respondedDocument = ResponseHelper.getBody(responseCreateDocument, Document.class);
    Assert.assertNotNull(respondedDocument);

    //load file/*from  w w w  .j  a v a 2 s .co  m*/
    String fileName = "sandbox.pdf";
    InputStream in = null;
    byte[] source = null;
    try {
        in = UserSession.class.getResourceAsStream("/" + fileName);
        source = IOUtils.toByteArray(in);
    } finally {
        IOUtils.closeQuietly(in);
    }
    ByteArrayBody fileBody = new ByteArrayBody(source, fileName);

    //Add document
    System.out.println(RESOURCE_DOCUMENT + "/upload?documentId=" + respondedDocument.getId());
    HttpResponse responseUploadAttachment = UserSession.user()
            .postFile(RESOURCE_DOCUMENT + "/upload?documentId=" + respondedDocument.getId(), fileBody);
    Assert.assertEquals(HttpStatus.OK, ResponseHelper.getStatusCode(responseUploadAttachment));
    Long attachmentId = ResponseHelper.getBody(responseUploadAttachment, Long.class);
    Assert.assertNotNull(attachmentId);

    String uri = RESOURCE_DOCUMENT + "/" + respondedDocument.getId() + "/download/" + attachmentId;
    HttpResponse response = UserSession.user().get(uri);
    Assert.assertEquals(HttpStatus.OK, ResponseHelper.getStatusCode(response));

    HttpEntity entity = response.getEntity();
    System.out.println(entity.getContentType());
    InputStream inStream = entity.getContent();
    InputStream inStreamExistingFile = new FileInputStream("./src/test/resources/sandbox.pdf");
    Assert.assertNotNull(inStream);
    Assert.assertNotNull(inStreamExistingFile);
    Assert.assertTrue(IOUtils.contentEquals(inStream, inStreamExistingFile));
}

From source file:com.ctctlabs.ctctwsjavalib.CTCTConnection.java

/**
 * Perform a multipart post request to the web service
 * @param link     URL to perform the post request
 * @param content  the string part//from  w  w  w . ja v  a  2  s  .c om
 * @param baData   the byte array part
 * @param fileName the file name in the byte array part
 * @return response entity content returned by the web service
 * @throws ClientProtocolException
 * @throws IOException
 * @author CL Kim
 */
InputStream doPostMultipartRequest(String link, String content, byte[] baData, String fileName)
        throws ClientProtocolException, IOException {
    HttpPost httppost = new HttpPost(link);

    StringBody sbody = new StringBody(content);
    FormBodyPart fbp1 = new FormBodyPart("imageatomxmlpart", sbody);
    fbp1.addField("Content-Type", "application/atom+xml");
    //fbp1.addField("Accept", "application/atom+xml");

    ByteArrayBody babody = new ByteArrayBody(baData, fileName);
    FormBodyPart fbp2 = new FormBodyPart("imagejpegpart", babody);
    fbp2.addField("Content-Type", "image/jpeg");
    fbp2.addField("Transfer-Encoding", "binary");
    //fbp2.addField("Accept", "application/atom+xml");

    MultipartEntity reqEntity = new MultipartEntity(); // HttpMultipartMode.STRICT is default, cannot be HttpMultipartMode.BROWSER_COMPATIBLE
    reqEntity.addPart(fbp1);
    reqEntity.addPart(fbp2);
    httppost.setEntity(reqEntity);
    if (accessToken != null)
        httppost.setHeader("Authorization", "Bearer " + accessToken); // for OAuth2.0
    HttpResponse response = httpclient.execute(httppost);

    if (response != null) {
        responseStatusCode = response.getStatusLine().getStatusCode();
        responseStatusReason = response.getStatusLine().getReasonPhrase();
        // If receive anything but a 201 status, return a null input stream
        if (responseStatusCode == HttpStatus.SC_CREATED) {
            return response.getEntity().getContent();
        }
        return null;
    } else {
        responseStatusCode = 0; // reset to initial default
        responseStatusReason = null; // reset to initial default
        return null;
    }
}

From source file:org.nasa.openspace.gc.geolocation.LocationActivity.java

public void executeMultipartPost() throws Exception {

    try {/*from   w w  w. jav a 2s.co m*/

        HttpClient client = new DefaultHttpClient();

        HttpPost post = new HttpPost("http://192.168.14.102/index.php/photos/upload");

        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

        Session.image.compress(Bitmap.CompressFormat.PNG, 100, byteStream);

        byte[] buffer = byteStream.toByteArray();

        ByteArrayBody body = new ByteArrayBody(buffer, "profile_image");

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("gambar", body);
        entity.addPart("nama", new StringBody(Session.name)); //POST nama
        entity.addPart("keterangan", new StringBody(Session.caption)); //POST keterangan
        entity.addPart("lat", new StringBody(lat)); //POST keterangan
        entity.addPart("lon", new StringBody(longt)); //POST keterangan
        post.setEntity(entity);

        System.out.println("post entity length " + entity.getContentLength());
        ResponseHandler handler = new BasicResponseHandler();

        String response = client.execute(post, handler);

    } catch (Exception e) {

        Log.e(e.getClass().getName(), e.getMessage());

    }

}

From source file:net.rcarz.jiraclient.RestClient.java

private JSON request(HttpEntityEnclosingRequestBase req, Issue.NewAttachment... attachments)
        throws RestException, IOException {
    if (attachments != null) {
        req.setHeader("X-Atlassian-Token", "nocheck");
        MultipartEntity ent = new MultipartEntity();
        for (Issue.NewAttachment attachment : attachments) {
            String filename = attachment.getFilename();
            Object content = attachment.getContent();
            if (content instanceof byte[]) {
                ent.addPart("file", new ByteArrayBody((byte[]) content, filename));
            } else if (content instanceof InputStream) {
                ent.addPart("file", new InputStreamBody((InputStream) content, filename));
            } else if (content instanceof File) {
                ent.addPart("file", new FileBody((File) content, filename));
            } else if (content == null) {
                throw new IllegalArgumentException("Missing content for the file " + filename);
            } else {
                throw new IllegalArgumentException(
                        "Expected file type byte[], java.io.InputStream or java.io.File but provided "
                                + content.getClass().getName() + " for the file " + filename);
            }/*from  w ww.j a va  2 s.  c o m*/
        }
        req.setEntity(ent);
    }
    return request(req);
}

From source file:org.apache.hadoop.hdfs.qjournal.server.TestJournalNodeImageUpload.java

private ContentBody genContent() throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
    new Random().nextBytes(randomBytes);
    bos.write(randomBytes);/* w w w .j  a v  a2 s. co m*/
    return new ByteArrayBody(bos.toByteArray(), "filename");
}