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:com.tmount.business.cloopen.restAPI.RestAPI.java

/**
* @brief            ?//  w  ww  .  j a v  a  2  s  .c o m
* @param accountSid      ?
* @param authToken      ?
* @param appId         id
* @param mediaName      ??
* @param mediaTxt      
* @param playTimes      
* @param to            ???
*/
public String LandingCalls(String accountSid, String authToken, String appId, String mediaName,
        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/LandingCalls?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
            StringBuilder bodyBuilder = new StringBuilder(
                    "<?xml version='1.0' encoding='utf-8'?><LandingCall>");
            bodyBuilder.append("<appId>").append(appId).append("</appId>");
            bodyBuilder.append("<mediaName>").append(mediaName).append("</mediaName>");
            bodyBuilder.append("<playTimes>").append(playTimes).append("</playTimes>");
            bodyBuilder.append("<to>").append(to).append("</to></LandingCall>");
            body = bodyBuilder.toString();

        } else {
            LandingCallsRequest landingCallsRequest = new LandingCallsRequest(appId, mediaName, playTimes, to);
            Gson gson = new Gson();
            body = gson.toJson(landingCallsRequest);
        }
        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

/**
 * ??/* w  w w  .j a  v a  2  s  . c  o  m*/
 * @param to  ?
 * @param body 
 * @param msgType             0:     1:65  
 * @param sms_type  ?          0:   1:  2???  3tomcat
 * @return
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public String SendSMS(String to, String body, String msgType, String sms_type)
        throws NoSuchAlgorithmException, KeyManagementException {
    String filePath = this.getClass().getClassLoader().getResource("config.properties").toString().substring(6);
    filePath = "/" + filePath;
    AgentSysInfo agentSysInfo = new AgentSysInfo();
    agentSysInfo = PropertiesUtil.getAgentSysInfo(filePath);
    String accountSid = agentSysInfo.getAccountSid();
    String authToken = agentSysInfo.getAuthToken();
    String appId = agentSysInfo.getAppId();
    String subAccountSid = agentSysInfo.getSub_account();
    String app_name = agentSysInfo.getApp_name();
    String reserve_date = agentSysInfo.getReserve_date();
    String reserve_address = agentSysInfo.getReserve_address();
    String sms_time = agentSysInfo.getSms_time();
    String reslut = "";
    // 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(port).append("/").append(softVer)
                .append("/Accounts/").append(accountSid).append("/SMS/TemplateSMS?sig=")//Messages   TemplateSMS
                .append(signature).toString();
        // HttpPost
        System.out.println("url:" + url);
        HttpPost httppost = new HttpPost(url);
        setHttpHeader(httppost);
        String src = accountSid + ":" + timestamp;
        String auth = eu.base64Encoder(src);
        httppost.setHeader("Authorization", auth);// base64(Id + ? + )
        String bodyData = null;
        logger.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~SMS is bigining  sms_type:"
                + sms_type);
        if (!JsonUtils.JSON_ENABLE) {
            // Body
            if (sms_type.equalsIgnoreCase("0"))//?
            {
                bodyData = (new StringBuilder("<?xml version='1.0' encoding='utf-8'?>")).append("<TemplateSMS>")
                        .append("<to>").append(to).append("</to>").append("<appId>").append(appId)
                        .append("</appId>").append("<templateId>4106</templateId>").append("<datas>")
                        .append("<data>" + app_name + "</data>").append("<data>" + body + "</data>")
                        /*.append("<data>"+sms_time+"</data>")*/
                        .append("</datas>").append("</TemplateSMS>").toString();
            } else if (sms_type.equalsIgnoreCase("1"))//
            {
                bodyData = (new StringBuilder("<?xml version='1.0' encoding='utf-8'?>")).append("<TemplateSMS>")
                        .append("<to>").append(to).append("</to>").append("<appId>").append(appId)
                        .append("</appId>").append("<templateId>1519</templateId>").append("<datas>")
                        .append("<data>" + body + "</data>").append("<data>" + sms_time + "</data>")
                        .append("</datas>").append("</TemplateSMS>").toString();
            } else if (sms_type.equalsIgnoreCase("2"))//????
            {
                bodyData = (new StringBuilder("<?xml version='1.0' encoding='utf-8'?>")).append("<TemplateSMS>")
                        .append("<to>").append(to).append("</to>").append("<appId>").append(appId)
                        .append("</appId>").append("<templateId>1520</templateId>").append("<datas>")
                        .append("<data>" + DatatimeUtil.getCurrentDate().toString() + "</data>")//?
                        .append("<data>" + body + "</data>")//??
                        .append("<data>" + reserve_date + "</data>")//?
                        .append("<data>" + reserve_address + "</data>")//??
                        .append("</datas>").append("</TemplateSMS>").toString();
            } else if (sms_type.equalsIgnoreCase("3"))//tomcat 
            {
                bodyData = (new StringBuilder("<?xml version='1.0' encoding='utf-8'?>")).append("<TemplateSMS>")
                        .append("<to>").append(to).append("</to>").append("<appId>").append(appId)
                        .append("</appId>").append("<templateId>1758</templateId>").append("<datas>")
                        .append("<data>" + body + "</data>")//?
                        .append("</datas>").append("</TemplateSMS>").toString();
            }
        } else {
            SendSMSRequest sendSMS = new SendSMSRequest(to, bodyData, msgType, appId, subAccountSid);
            Gson gson = new Gson();
            bodyData = gson.toJson(sendSMS);
        }
        System.out.println("?? : request _" + bodyData);
        BasicHttpEntity requestBody = new BasicHttpEntity();
        requestBody.setContent(new ByteArrayInputStream(bodyData.getBytes("UTF-8")));
        requestBody.setContentLength(bodyData.getBytes("UTF-8").length);
        httppost.setEntity(requestBody);
        // 
        HttpResponse response = httpclient.execute(httppost);
        // ???
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            reslut = EntityUtils.toString(entity, "UTF-8");
        }
        // ?HTTP??
        EntityUtils.consume(entity);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 
        httpclient.getConnectionManager().shutdown();
    }
    //???
    return reslut;
}

From source file:com.ibm.sbt.test.lib.MockSerializer.java

private HttpResponse buildResponse(Header[] allHeaders, int statusCode, String reasonPhrase,
        String serializedEntity) {
    BasicHttpResponse r = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 0), statusCode, reasonPhrase);
    r.setHeaders(allHeaders);// w  ww .j  a  v a  2s  . c o  m

    if (serializedEntity != null) {
        BasicHttpEntity e = new BasicHttpEntity();
        // TODO: use content-encoding header
        try {
            e.setContent(new ByteArrayInputStream(serializedEntity.getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e1) {
            throw new UnsupportedOperationException(e1);
        }
        for (Header h : allHeaders) {
            if (h.getName().equalsIgnoreCase("Content-Type")) {
                e.setContentType(h.getValue());
            }
        }
        e.setContentLength(serializedEntity.length());
        r.setEntity(e);
    }
    return r;
}

From source file:org.restcomm.camelgateway.slee.CamelGatewaySbb.java

private void pushContent(HttpUriRequest request, String contentType, String contentEncoding, byte[] content) {

    // TODO: check other preconditions?
    if (contentType != null && content != null && request instanceof HttpEntityEnclosingRequest) {
        BasicHttpEntity entity = new BasicHttpEntity();
        entity.setContent(new ByteArrayInputStream(content));
        entity.setContentLength(content.length);
        entity.setChunked(false);//from  w  w  w  .  jav  a2s  .c om
        if (contentEncoding != null)
            entity.setContentEncoding(contentEncoding);
        entity.setContentType(contentType);
        HttpEntityEnclosingRequest rr = (HttpEntityEnclosingRequest) request;
        rr.setEntity(entity);
    }

}

From source file:org.apache.hadoop.gateway.dispatch.CappedBufferHttpEntityTest.java

@Test
public void testGetContentLength() throws Exception {
    String input = "0123456789";
    BasicHttpEntity basic;
    CappedBufferHttpEntity replay;/*from w  ww.  ja v a  2 s  .c om*/

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    replay = new CappedBufferHttpEntity(basic, 5);
    assertThat(replay.getContentLength(), is(-1L));

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    basic.setContentLength(input.length());
    replay = new CappedBufferHttpEntity(basic, 5);
    assertThat(replay.getContentLength(), is(10L));
}

From source file:org.apache.hadoop.gateway.dispatch.PartiallyRepeatableHttpEntityTest.java

@Test
public void testGetContentLength() throws Exception {
    String input = "0123456789";
    BasicHttpEntity basic;
    PartiallyRepeatableHttpEntity replay;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    replay = new PartiallyRepeatableHttpEntity(basic, 5);
    assertThat(replay.getContentLength(), is(-1L));

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    basic.setContentLength(input.length());
    replay = new PartiallyRepeatableHttpEntity(basic, 5);
    assertThat(replay.getContentLength(), is(10L));
}

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

/**
 * Write the stream to a temporary storage and calculate the content length
 * @param entity HTTPEntity/* w w  w .  ja v  a2 s .  c  om*/
 * @param messageFormatter message formatter
 * @param msgContext current message context
 * @param format message format
 * @throws IOException if an exception occurred while writing data
 */
private void setStreamAsTempData(BasicHttpEntity entity, MessageFormatter messageFormatter,
        MessageContext msgContext, OMOutputFormat format) throws IOException {
    TemporaryData serialized = new TemporaryData(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:org.apache.synapse.transport.nhttp.ServerHandler.java

/**
 * Commit the response to the connection. Processes the response through the configured
 * HttpProcessor and submits it to be sent out. Re-Throws exceptions, after closing connections
 * @param conn the connection being processed
 * @param response the response to commit over the connection
 * @throws IOException if an IO error occurs while sending the response
 * @throws HttpException if a HTTP protocol violation occurs while sending the response
 *//*from  w  ww.  ja v  a2  s.  c om*/
public void commitResponse(final NHttpServerConnection conn, final HttpResponse response)
        throws IOException, HttpException {
    try {
        BasicHttpEntity entity = (BasicHttpEntity) response.getEntity();
        Header[] headers = response.getAllHeaders();
        int contentLength = -1;
        if (canResponseHaveBody(response, conn)) {
            if (entity == null) {
                entity = new BasicHttpEntity();
            }
            for (Header header : headers) {
                if (header.getName().equals(HTTP.CONTENT_LEN) && Integer.parseInt(header.getValue()) > 0) {
                    contentLength = Integer.parseInt(header.getValue());
                    response.removeHeader(header);
                }
            }
            if (contentLength != -1) {
                entity.setChunked(false);
                entity.setContentLength(contentLength);
            } else {
                entity.setChunked(true);
            }
        } else {
            if (entity != null) {
                entity.setChunked(false);
                entity.setContentLength(contentLength);
            }
        }
        response.setEntity(entity);
        conn.suspendInput();
        HttpContext context = conn.getContext();
        httpProcessor.process(response, context);
        conn.getContext().setAttribute(NhttpConstants.RES_TO_CLIENT_WRITE_START_TIME,
                System.currentTimeMillis());
        conn.submitResponse(response);
    } catch (HttpException e) {
        shutdownConnection(conn, true, e.getMessage());
        throw e;
    } catch (IOException e) {
        shutdownConnection(conn, true, e.getMessage());
        throw e;
    }
}