Example usage for org.apache.http.entity BasicHttpEntity setContentLength

List of usage examples for org.apache.http.entity BasicHttpEntity setContentLength

Introduction

In this page you can find the example usage for org.apache.http.entity BasicHttpEntity setContentLength.

Prototype

public void setContentLength(long j) 

Source Link

Usage

From source file:be.cytomine.client.HttpClient.java

public int post(String data) throws IOException {
    log.debug("Post " + URL.getPath());
    HttpPost httpPost = new HttpPost(URL.toString());
    if (isAuthByPrivateKey) {
        httpPost.setHeaders(headersArray);
    }/*from  w w w. j  av a 2  s .c o m*/
    log.debug("Post send :" + data.replace("\n", ""));
    //write data
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream(data.getBytes()));
    entity.setContentLength((long) data.getBytes().length);
    httpPost.setEntity(entity);
    response = client.execute(targetHost, httpPost, localcontext);
    return response.getStatusLine().getStatusCode();
}

From source file:be.cytomine.client.HttpClient.java

public int put(String data) throws IOException {
    log.debug("Put " + URL.getPath());
    HttpPut httpPut = new HttpPut(URL.toString());
    if (isAuthByPrivateKey) {
        httpPut.setHeaders(headersArray);
    }// www.j ava2s .c o  m
    log.debug("Put send :" + data.replace("\n", ""));
    //write data
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream(data.getBytes()));
    entity.setContentLength((long) data.getBytes().length);
    httpPut.setEntity(entity);
    response = client.execute(targetHost, httpPut, localcontext);
    return response.getStatusLine().getStatusCode();
}

From source file:jscover.server.PersistentStaticHttpServer.java

protected void sendOkContent(HttpServerConnection conn) throws IOException, HttpException {
    // send a 200 OK with the static content
    BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
    BasicHttpEntity entity = new BasicHttpEntity();
    byte[] message = content.getBytes(Charset.forName("UTF-8"));
    entity.setContent(new ByteArrayInputStream(message));
    entity.setContentLength(message.length);
    response.setEntity(entity);/*from  ww  w  . j a  v  a2  s.  c o  m*/

    // force Content-Length header so the client doesn't expect us to close the connection to end the response
    response.addHeader("Content-Length", String.valueOf(message.length));

    conn.sendResponseHeader(response);
    conn.sendResponseEntity(response);
    conn.flush();
    logger.log(FINE, "Sent 200 OK");
}

From source file:org.mycard.net.network.AndroidHttpClientConnection.java

/***
 * Return the next response entity./* w w w . j  ava  2s . c  o m*/
 * @param headers contains values for parsing entity
 * @see HttpClientConnection#receiveResponseEntity(HttpResponse response)
 */
public HttpEntity receiveResponseEntity(final Headers headers) {
    assertOpen();
    BasicHttpEntity entity = new BasicHttpEntity();

    long len = determineLength(headers);
    if (len == ContentLengthStrategy.CHUNKED) {
        entity.setChunked(true);
        entity.setContentLength(-1);
        entity.setContent(new ChunkedInputStream(inbuffer));
    } else if (len == ContentLengthStrategy.IDENTITY) {
        entity.setChunked(false);
        entity.setContentLength(-1);
        entity.setContent(new IdentityInputStream(inbuffer));
    } else {
        entity.setChunked(false);
        entity.setContentLength(len);
        entity.setContent(new ContentLengthInputStream(inbuffer, len));
    }

    String contentTypeHeader = headers.getContentType();
    if (contentTypeHeader != null) {
        entity.setContentType(contentTypeHeader);
    }
    String contentEncodingHeader = headers.getContentEncoding();
    if (contentEncodingHeader != null) {
        entity.setContentEncoding(contentEncodingHeader);
    }

    return entity;
}

From source file:org.apache.synapse.transport.nhttp.Axis2HttpRequest.java

/**
 * Write the stream to a temporary storage and calculate the content length
 *
 * @param entity HTTPEntity//from  w  w w  . jav  a 2 s  .c  o m
 * @throws IOException if an exception occurred while writing data
 */
private void setStreamAsTempData(BasicHttpEntity entity) throws IOException {
    OverflowBlob serialized = new OverflowBlob(256, 4096, "http-nio_", ".dat");
    OutputStream out = serialized.getOutputStream();
    try {
        messageFormatter.writeTo(msgContext, format, out, true);
    } finally {
        out.close();
    }
    msgContext.setProperty(NhttpConstants.SERIALIZED_BYTES, serialized);
    entity.setContentLength(serialized.getLength());
}

From source file:com.tmount.business.cloopen.restAPI.RestAPI.java

public String getSubAccountSid(String accountSid, String authToken, String appId)
        throws NoSuchAlgorithmException, KeyManagementException {
    // ?/*from   w  ww .  j a  v a  2  s.c  o  m*/
    String result = "";
    // HttpClient
    CcopHttpClient chc = new CcopHttpClient();
    DefaultHttpClient httpclient = chc.registerSSL("app.cloopen.com", "TLS", 8883, "https");
    try {
        // URL
        String timestamp = DateUtil.dateToStr(new Date(), DateUtil.DATE_TIME_NO_SLASH);
        // md5(Id +? + )
        String sig = accountSid + authToken + timestamp;
        // MD5
        EncryptUtil eu = new EncryptUtil();
        String signature = eu.md5Digest(sig);
        String url = (new StringBuilder(hostname)).append("/").append(softVer).append("/Accounts/")
                .append(accountSid).append("/GetSubAccounts?sig=").append(signature).toString();
        // HttpPost
        System.out.println("url:" + url);
        HttpPost httppost = new HttpPost(url);
        setHttpHeader(httppost);
        String src = accountSid + ":" + timestamp;
        // base64(Id + ? +)
        String auth = eu.base64Encoder(src);
        httppost.setHeader("Authorization", auth);

        String body = null;
        if (!JsonUtils.JSON_ENABLE) {
            // Body
            body = (new StringBuilder("<?xml version='1.0' encoding='utf-8'?><SubAccount>").append("<appId>"))
                    .append(appId).append("</appId>").append("<startNo>1</startNo>")
                    .append("<offset>100</offset></SubAccount>").toString();
        }
        System.out.println("CreateSubAccount : request _" + body);

        BasicHttpEntity requestBody = new BasicHttpEntity();
        requestBody.setContent(new ByteArrayInputStream(body.getBytes("UTF-8")));
        requestBody.setContentLength(body.getBytes("UTF-8").length);
        httppost.setEntity(requestBody);

        // 
        HttpResponse response = httpclient.execute(httppost);

        // ???
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            result = EntityUtils.toString(entity, "UTF-8");
        }
        // ?HTTP??
        EntityUtils.consume(entity);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 
        httpclient.getConnectionManager().shutdown();
    }
    return result;
}

From source file:com.tmount.business.cloopen.restAPI.RestAPI.java

/**
* @brief               ??//from   w w w  .  j ava  2s.  com
* @param accountSid         ?
* @param authToken         ?
* @param appId            id
* @param friendlyName      
* @param status            ?
* @return Httppost          ???
* @throws NoSuchAlgorithmException
* @throws KeyManagementException  jdbc.properties
*/
public String CreateSubAccount(String accountSid, String authToken, String appId, String friendlyName,
        String status) throws NoSuchAlgorithmException, KeyManagementException {
    // ?
    String result = "";
    // HttpClient
    CcopHttpClient chc = new CcopHttpClient();
    DefaultHttpClient httpclient = chc.registerSSL(domain, "TLS", 8883, "https");
    try {
        // URL
        String timestamp = DateUtil.dateToStr(new Date(), DateUtil.DATE_TIME_NO_SLASH);
        // md5(Id +? + )
        String sig = accountSid + authToken + timestamp;
        // MD5
        EncryptUtil eu = new EncryptUtil();
        String signature = eu.md5Digest(sig);
        String url = (new StringBuilder(hostname)).append(":").append(port).append("/").append(softVer)
                .append("/Accounts/").append(accountSid).append("/SubAccounts?sig=").append(signature)
                .toString();
        // HttpPost
        HttpPost httppost = new HttpPost(url);
        setHttpHeader(httppost);
        String src = accountSid + ":" + timestamp;
        // base64(Id + ? +)
        String auth = eu.base64Encoder(src);
        httppost.setHeader("Authorization", auth);
        String body = null;
        if (!JsonUtils.JSON_ENABLE) {
            // Body
            body = (new StringBuilder("<?xml version='1.0' encoding='utf-8'?><SubAccount>").append("<appId>"))
                    .append(appId).append("</appId>").append("<friendlyName>").append(friendlyName)
                    .append("</friendlyName>").append("</SubAccount>").toString();
        } else {
            SubAccountCreate subAccount = new SubAccountCreate(appId, friendlyName, accountSid);
            Gson gson = new Gson();
            body = gson.toJson(subAccount);
        }
        System.out.println("CreateSubAccount : request _" + body);
        BasicHttpEntity requestBody = new BasicHttpEntity();
        requestBody.setContent(new ByteArrayInputStream(body.getBytes("UTF-8")));
        requestBody.setContentLength(body.getBytes("UTF-8").length);
        httppost.setEntity(requestBody);
        // 
        HttpResponse response = httpclient.execute(httppost);
        // ???
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            result = EntityUtils.toString(entity, "UTF-8");
        }
        // ?HTTP??
        EntityUtils.consume(entity);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 
        httpclient.getConnectionManager().shutdown();
    }
    return result;
}

From source file:com.tmount.business.cloopen.restAPI.RestAPI.java

/**
 * ??//ww w .j a  v  a  2s. c  om
 * @param accountSid
 * @param authToken
 * @param appId
 * @param subAccountSid
 * @return
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public String CloseSubAccount(String accountSid, String authToken, String appId, String subAccountSid)
        throws NoSuchAlgorithmException, KeyManagementException {
    // ?
    String result = "";
    // HttpClient
    CcopHttpClient chc = new CcopHttpClient();
    DefaultHttpClient httpclient = chc.registerSSL("app.cloopen.com", "TLS", 8883, "https");
    try {
        // URL
        String timestamp = DateUtil.dateToStr(new Date(), DateUtil.DATE_TIME_NO_SLASH);
        // md5(Id +? + )
        String sig = accountSid + authToken + timestamp;
        // MD5
        EncryptUtil eu = new EncryptUtil();
        String signature = eu.md5Digest(sig);
        String url = (new StringBuilder(hostname)).append("/").append(softVer).append("/Accounts/")
                .append(accountSid).append("/CloseSubAccount?sig=").append(signature).toString();
        // HttpPost
        System.out.println("url:" + url);
        HttpPost httppost = new HttpPost(url);
        setHttpHeader(httppost);
        String src = accountSid + ":" + timestamp;
        // base64(Id + ? +)
        String auth = eu.base64Encoder(src);
        httppost.setHeader("Authorization", auth);

        String body = null;
        if (!JsonUtils.JSON_ENABLE) {
            // Body
            body = (new StringBuilder("<?xml version='1.0' encoding='utf-8'?><SubAccount>").append("<appId>"))
                    .append(appId).append("</appId>")
                    .append("<subAccountSid>" + subAccountSid + "</subAccountSid> </SubAccount>").toString();
        }
        System.out.println("CloseSubAccount : request _" + body);

        BasicHttpEntity requestBody = new BasicHttpEntity();
        requestBody.setContent(new ByteArrayInputStream(body.getBytes("UTF-8")));
        requestBody.setContentLength(body.getBytes("UTF-8").length);
        httppost.setEntity(requestBody);

        // 
        HttpResponse response = httpclient.execute(httppost);

        // ???
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            result = EntityUtils.toString(entity, "UTF-8");
        }
        // ?HTTP??
        EntityUtils.consume(entity);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 
        httpclient.getConnectionManager().shutdown();
    }
    return result;
}

From source file:com.tmount.business.cloopen.restAPI.RestAPI.java

/**
* @brief            ??// w w  w . j  av a  2 s .c om
* @param subAccountSid   ??   
* @param subToken      ??
* @param voipAccount   VoIP?
* @param from         ??
* @param to            ??
* @return Httppost       ???
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public String CallBack(String subAccountSid, String subToken, String voipAccount, String from, String to)
        throws NoSuchAlgorithmException, KeyManagementException {
    // ?
    String result = "";
    // HttpClient
    CcopHttpClient chc = new CcopHttpClient();
    DefaultHttpClient httpclient = chc.registerSSL("sandboxapp.cloopen.com", "TLS", 8883, "https");
    try {
        // URL
        String timestamp = DateUtil.dateToStr(new Date(), DateUtil.DATE_TIME_NO_SLASH);// 
        // md5(?Id + ?? + )
        String sig = subAccountSid + subToken + timestamp;
        // MD5
        EncryptUtil eu = new EncryptUtil();
        String signature = eu.md5Digest(sig);

        String url = (new StringBuilder(hostname)).append(":").append(port).append("/").append(softVer)
                .append("/SubAccounts/").append(subAccountSid).append("/Calls/Callback?sig=").append(signature)
                .toString();
        // HttpPost
        HttpPost httppost = new HttpPost(url);
        setHttpHeader(httppost);
        String src = subAccountSid + ":" + timestamp;
        String auth = eu.base64Encoder(src);
        httppost.setHeader("Authorization", auth);// base64(?Id + ? + )

        String body = null;
        if (!JsonUtils.JSON_ENABLE) {

            // Body
            body = (new StringBuilder("<?xml version='1.0' encoding='utf-8'?><CallBack>").append("<from>")
                    .append(from).append("</from>").append("<to>").append(to).append("</to></CallBack>")
                    .toString());
        } else {
            CallBackRequest callBackRequest = new CallBackRequest(subAccountSid, voipAccount, from, to);
            Gson gson = new Gson();
            body = gson.toJson(callBackRequest);
        }
        System.out.println("CreateSubAccount : request _" + body);

        BasicHttpEntity requestBody = new BasicHttpEntity();
        requestBody.setContent(new ByteArrayInputStream(body.getBytes("UTF-8")));
        requestBody.setContentLength(body.getBytes("UTF-8").length);
        httppost.setEntity(requestBody);

        // 
        HttpResponse response = httpclient.execute(httppost);

        // ???
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            result = EntityUtils.toString(entity, "UTF-8");
        }
        // ?HTTP??
        EntityUtils.consume(entity);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 
        httpclient.getConnectionManager().shutdown();
    }
    return result;
}

From source file:com.tmount.business.cloopen.restAPI.RestAPI.java

/**
* @brief            ??//from   w  w  w.  ja  v  a2 s .c o m
* @param accountSid      ?
* @param authToken      ?
* @param appId         id
* @param verifyCode      ?????4-20?
* @param playTimes      1?3
* @param to            ??
*/
public String VoiceVerifyCode(String accountSid, String authToken, String appId, String verifyCode,
        String playTimes, String to) throws NoSuchAlgorithmException, KeyManagementException {
    // ?
    String result = "";
    // HttpClient
    CcopHttpClient chc = new CcopHttpClient();
    DefaultHttpClient httpclient = chc.registerSSL("sandboxapp.cloopen.com", "TLS", 8883, "https");
    try {
        // URL
        String timestamp = DateUtil.dateToStr(new Date(), DateUtil.DATE_TIME_NO_SLASH);
        // md5(Id +? + )
        String sig = accountSid + authToken + timestamp;
        // MD5
        EncryptUtil eu = new EncryptUtil();
        String signature = eu.md5Digest(sig);
        String url = (new StringBuilder(hostname)).append(":").append(port).append("/").append(softVer)
                .append("/Accounts/").append(accountSid).append("/Calls/VoiceVerify?sig=").append(signature)
                .toString();
        // HttpPost
        HttpPost httppost = new HttpPost(url);
        setHttpHeader(httppost);
        String src = accountSid + ":" + timestamp;
        // base64(Id + ? +)
        String auth = eu.base64Encoder(src);
        httppost.setHeader("Authorization", auth);

        String body = null;
        if (!JsonUtils.JSON_ENABLE) {
            // Body
            body = (new StringBuilder("<?xml version='1.0' encoding='utf-8'?><VoiceVerify>").append("<appId>"))
                    .append(appId).append("</appId>").append("<verifyCode>").append(verifyCode)
                    .append("</verifyCode>").append("<playTimes>").append(playTimes).append("</playTimes>")
                    .append("<to>").append(to).append("</to></VoiceVerify>").toString();
        } else {

            VoiceVerifyCodeRequest verifyCodeRequest = new VoiceVerifyCodeRequest(appId, verifyCode, playTimes,
                    to);
            Gson gson = new Gson();
            body = gson.toJson(verifyCodeRequest);
        }
        System.out.println("CreateSubAccount : request _" + body);

        BasicHttpEntity requestBody = new BasicHttpEntity();
        requestBody.setContent(new ByteArrayInputStream(body.getBytes("UTF-8")));
        requestBody.setContentLength(body.getBytes("UTF-8").length);
        httppost.setEntity(requestBody);

        // 
        HttpResponse response = httpclient.execute(httppost);

        // ???
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            result = EntityUtils.toString(entity, "UTF-8");
        }
        // ?HTTP??
        EntityUtils.consume(entity);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 
        httpclient.getConnectionManager().shutdown();
    }
    return result;
}