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:org.botlibre.sdk.SDKConnection.java

public String POSTFILE(String url, String path, String name, String xml) {
    if (this.debug) {
        System.out.println("POST: " + url);
        System.out.println("file: " + path);
        System.out.println("XML: " + xml);
    }/*from w  w  w  .j  a v a  2 s . co  m*/
    String result = "";
    try {
        File file = new File(path);
        FileInputStream stream = new FileInputStream(file);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        int read = 0;
        byte[] buffer = new byte[4096];
        while ((read = stream.read(buffer)) != -1) {
            output.write(buffer, 0, read);
        }
        byte[] byte_arr = output.toByteArray();
        stream.close();
        ByteArrayBody fileBody = new ByteArrayBody(byte_arr, name);

        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        multipartEntity.addPart("file", fileBody);
        multipartEntity.addPart("xml", new StringBody(xml));

        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = null;

        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(multipartEntity);
        response = httpclient.execute(httppost);

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            result = EntityUtils.toString(entity, HTTP.UTF_8);
        }

        if ((response.getStatusLine().getStatusCode() != 200)
                && (response.getStatusLine().getStatusCode() != 204)) {
            this.exception = new SDKException("" + response.getStatusLine().getStatusCode() + " : " + result);
            throw this.exception;
        }

    } catch (Exception exception) {
        this.exception = new SDKException(exception);
        throw this.exception;
    }
    return result;
}

From source file:com.lehman.ic9.net.httpClient.java

/**
 * Sets request information for the type of POST request. This is determined 
 * by the post type provided./*w  w  w  .j av a2 s. co m*/
 * @param postTypeStr is a String with the postType.
 * @param Obj is a Javascript object to set for the request.
 * @param ContentType is a String with the content-type for the custom request.
 * @throws ic9exception Exception
 * @throws UnsupportedEncodingException Exception
 */
@SuppressWarnings("unchecked")
private void setPostInfo(String postTypeStr, Object Obj, String ContentType)
        throws ic9exception, UnsupportedEncodingException {
    postType pt = this.getPostType(postTypeStr);
    if (pt == postType.URL_ENCODED) {
        Map<String, Object> jobj = (Map<String, Object>) Obj;
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        for (String key : jobj.keySet()) {
            Object val = jobj.get(key);
            nvps.add(new BasicNameValuePair(key, val.toString()));
        }
        this.respEnt = new UrlEncodedFormEntity(nvps);
    } else if (pt == postType.MULTIPART) {
        MultipartEntityBuilder mpEntBuilder = MultipartEntityBuilder.create();
        Map<String, Object> jobj = (Map<String, Object>) Obj;
        for (String key : jobj.keySet()) {
            Map<String, Object> part = (Map<String, Object>) jobj.get(key);
            if (part.containsKey("name") && part.containsKey("data")) {
                String pkey = (String) part.get("name");
                if (part.get("data") instanceof byte[]) {
                    byte[] data = (byte[]) part.get("data");
                    mpEntBuilder.addPart(key, new ByteArrayBody(data, pkey));
                } else if (part.get("data") instanceof String) {
                    String data = (String) part.get("data");
                    mpEntBuilder.addPart(key,
                            new StringBody(data, org.apache.http.entity.ContentType.DEFAULT_TEXT));
                }
            } else
                throw new ic9exception(
                        "httpClient.setPotInfo(): Multipart from data expects and object of httpPart objects.");
        }
        this.respEnt = mpEntBuilder.build();
    } else {
        if (Obj instanceof String) {
            StringEntity se = new StringEntity((String) Obj);
            if (ContentType != null)
                se.setContentType(ContentType);
            else
                throw new ic9exception(
                        "httpClient.setPostInfo(): For custom postType, the third argument for content-type must be set.");
            this.respEnt = se;
        } else if (Obj instanceof Map) {
            Map<String, Object> tobj = (Map<String, Object>) Obj;

            if (tobj.containsKey("data") && tobj.get("data") instanceof byte[]) {
                if (ContentType != null) {
                    ByteArrayEntity bae = new ByteArrayEntity((byte[]) Obj);
                    bae.setContentType(ContentType);
                    this.respEnt = bae;
                } else
                    throw new ic9exception(
                            "httpClient.setPostInfo(): For custom postType, the third argument for content-type must be set.");
            } else
                throw new ic9exception(
                        "httpClient.setPostInfo(): Provided object is not of type Buffer or is missing 'data' attribute. (data should be byte[])");
        } else
            throw new ic9exception(
                    "httpClient.setPostInfo(): Second argument to POST call expecting String or Buffer object.");
    }
}

From source file:service.OrderService.java

private String sendRequestForUnloadInShop(Order order, ServiceResult result) throws Exception {
    List<String> missing = new ArrayList();
    List<String> directionNames = new ArrayList();
    for (Direction dir : order.getDirections()) {
        String dirName = (dir.getNameForShop() != null ? dir.getNameForShop() : "");
        if (dirName.isEmpty()) {
            missing.add(// ww w. j  a  v  a  2  s  . c  o m
                    "? ?    ? ? "
                            + dir.getName());
        }
        directionNames.add(dirName);
    }
    String orderName = "";
    if (order.getOrderType() != null && order.getOrderType().getNameForShop() != null) {
        orderName = order.getOrderType().getNameForShop();
    }
    if (orderName.isEmpty()) {
        missing.add(
                "? ?    ?  ");
    }
    String subject = (order.getSubject() != null ? order.getSubject() : "");
    if (subject.isEmpty()) {
        missing.add(" ");
    }
    String price = (order.getCost() != null ? order.getCost().toString() : "0");
    String numberOfPages = (order.getNumberOfPages() != null ? order.getNumberOfPages() : "");
    if (numberOfPages.isEmpty()) {
        missing.add("? ?");
    }
    String fileName = "order" + order.getOrderId() + ".zip";

    if (missing.isEmpty()) {
        String url = "http://zaochnik5.ru/up/uploadfile.php";
        HttpPost post = new HttpPost(url);
        MultipartEntityBuilder multipart = MultipartEntityBuilder.create();
        multipart.addTextBody("type_work", orderName);
        multipart.addTextBody("name_work", subject);
        multipart.addTextBody("price", price);
        multipart.addTextBody("table_of_contents", "-");
        for (String dirName : directionNames) {
            multipart.addTextBody("napravlenie", dirName);
        }
        multipart.addTextBody("kol-vo_str", numberOfPages);
        multipart.addTextBody("fail", fileName);
        multipart.addTextBody("order_number", order.getOrderId().toString());
        multipart.addTextBody("kol-vo_order", "1");
        multipart.addTextBody("published", "0");
        multipart.addTextBody("srvkey", "8D9ucTqL4Ga2ZkLCmctR");
        byte[] zipBytes = getZipAllReadyFiles(order);
        multipart.addPart("upload", new ByteArrayBody(zipBytes, fileName));
        HttpEntity ent = multipart.build();
        post.setEntity(ent);
        HttpClient client = HttpClients.createDefault();
        HttpResponse response = client.execute(post);
        return IOUtils.toString(response.getEntity().getContent());
    } else {
        String missingStr = "";
        for (String str : missing) {
            missingStr += str + ", ";
        }
        result.addError(
                "?  ,  ?  :"
                        + missingStr);
        return "";
    }
}

From source file:co.beem.project.beem.FbTextService.java

private void uploadPicture(ImageMessageInQueue imageMessageInQueue, String pageId, String accessToken,
        String message) throws ClientProtocolException, IOException {
    String url = String.format(
            "https://graph.facebook.com/v2.3/%s/photos/?access_token=%s&published=false&message=%s", pageId,
            accessToken, message);// ww  w .  j a va  2  s  .c  o m
    HttpPost post = new HttpPost(url);
    HttpClient client = new DefaultHttpClient();
    //Image attaching
    MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
    File file = new File(imageMessageInQueue.getLocalPath());
    Bitmap bi = decodeFile(file);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bi.compress(Bitmap.CompressFormat.JPEG, 65, baos);
    byte[] data = baos.toByteArray();
    ByteArrayBody byteArrayBody = new ByteArrayBody(data, file.getName());
    //multipartEntity.addBinaryBody("source", file, ContentType.create("image/jpeg"), file.getName());
    multipartEntity.addPart("source", byteArrayBody);
    post.setEntity(multipartEntity.build());
    HttpResponse response = client.execute(post);
    HttpEntity resEntity = response.getEntity();
    final String response_str = EntityUtils.toString(resEntity);
    if (FbTextApplication.isDebug)
        Log.v(TAG, "response entity: " + response_str);
    int statusCode = response.getStatusLine().getStatusCode();
    if (FbTextApplication.isDebug)
        Log.v(TAG, "response status code: " + statusCode);

    //get image link here
    if (200 != statusCode) {
        sendBroadcastPhotoResult(false, imageMessageInQueue, "");
        // update database this failure
        saveMessageImageSentStatus(imageMessageInQueue, false);
    } else
        try {
            String photoPostId = new Gson().fromJson(response_str, FbPost.class).getId();
            URL fbPhoto = new URL(
                    String.format("https://graph.facebook.com/v2.3/%s?access_token=%s&fields=images",
                            photoPostId, accessToken));
            HttpURLConnection urlConnection = (HttpURLConnection) fbPhoto.openConnection();
            InputStream inputStream = urlConnection.getInputStream();
            String postDetailString = "";
            if (null != inputStream)
                postDetailString = getStringFromInputStream(inputStream);
            if (FbTextApplication.isDebug)
                Log.v(TAG, postDetailString);
            if (postDetailString != null && postDetailString.length() > 1) {
                FbPhoto photo = new Gson().fromJson(postDetailString, FbPhoto.class);
                if (photo != null && photo.getImages() != null) {
                    boolean isSentLinkSuccess = true;
                    try {
                        BeemChatManager chatManager = getChatManager();
                        if (chatManager != null) {
                            ChatAdapter adapter = chatManager.getChat(imageMessageInQueue.getjIdWithRes());
                            Log.e(TAG, "jId with res: " + imageMessageInQueue.getjIdWithRes());
                            BeemMessage msgToSend = new BeemMessage(imageMessageInQueue.getjIdWithRes(),
                                    BeemMessage.MSG_TYPE_CHAT);
                            msgToSend.setBody(" sent you a photo " + photo.getImages().get(0).getSource());
                            if (adapter != null) {
                                adapter.sendMessage(msgToSend);
                            } else {
                                IChat newChat = chatManager.createChat(imageMessageInQueue.getjIdWithRes(),
                                        null);
                                newChat.sendMessage(msgToSend);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        isSentLinkSuccess = false;
                    }

                    sendBroadcastPhotoResult(isSentLinkSuccess, imageMessageInQueue,
                            photo.getImages().get(0).getSource());
                    // save image as sent
                    saveMessageImageSentStatus(imageMessageInQueue, isSentLinkSuccess);

                    //sleep a while after sent successfull
                    try {
                        Thread.sleep(3000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            sendBroadcastPhotoResult(false, imageMessageInQueue, " ");
            saveMessageImageSentStatus(imageMessageInQueue, false);
        }
}

From source file:org.ednovo.gooru.application.server.service.uploadServlet.java

public String fileUpload(byte[] bytes, String data, String fileName, Long fileSize, String urlVal)
        throws Exception {
    String ret = "";
    logger.info("upload Url:::" + urlVal);
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost httppost = new HttpPost(urlVal);
    MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
    ByteArrayBody bab = new ByteArrayBody(bytes, fileName);
    reqEntity.addPart("image", bab);
    httppost.setEntity(reqEntity.build());
    HttpResponse response = httpClient.execute(httppost);
    HttpEntity resEntity = response.getEntity();
    if (resEntity != null) {
        ret = EntityUtils.toString(resEntity);
    }/*from  www  .  j a  v a  2 s  .c o  m*/
    logger.info("upload response:::" + ret);
    return ret;
}