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

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

Introduction

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

Prototype

public void setContent(InputStream inputStream) 

Source Link

Usage

From source file:org.mobicents.slee.enabler.rest.client.RESTClientEnablerChildSbb.java

@Override
public void execute(RESTClientEnablerRequest request) throws Exception {

    // validate request
    if (request == null) {
        throw new NullPointerException("request is null");
    }/*  w ww  .j a v a 2s  .c o m*/
    if (request.getType() == null) {
        throw new NullPointerException("request type is null");
    }
    if (request.getUri() == null) {
        throw new NullPointerException("request uri is null");
    }

    // create http request
    HttpUriRequest httpRequest = null;
    switch (request.getType()) {
    case DELETE:
        httpRequest = new HttpDelete(request.getUri());
        break;
    case GET:
        httpRequest = new HttpGet(request.getUri());
        break;
    case POST:
        httpRequest = new HttpPost(request.getUri());
        break;
    case PUT:
        httpRequest = new HttpPut(request.getUri());
        break;
    default:
        throw new IllegalArgumentException("unknown request type");
    }

    // add headers, if any
    if (request.getHeaders() != null) {
        for (Header h : request.getHeaders()) {
            httpRequest.addHeader(h);
        }
    }

    // sign request using oauth, if needed
    if (request.getOAuthConsumer() != null) {
        request.getOAuthConsumer().sign(httpRequest);
    }

    // add content, if any
    if (request.getContent() != null) {
        if (!(httpRequest instanceof HttpEntityEnclosingRequest)) {
            throw new IllegalArgumentException("request includes content but type does not allows content");
        }
        if (request.getContentType() == null) {
            throw new IllegalArgumentException("request includes content but no content type");
        }
        BasicHttpEntity entity = new BasicHttpEntity();
        entity.setContent(request.getContent());
        if (request.getContentEncoding() != null)
            entity.setContentEncoding(request.getContentEncoding());
        entity.setContentType(request.getContentType());
        ((HttpEntityEnclosingRequest) httpRequest).setEntity(entity);
    }

    // get http client activity and attach to related aci
    HttpClientActivity activity = httpProvider.createHttpClientActivity(true, null);
    ActivityContextInterface aci = httpClientActivityContextInterfaceFactory
            .getActivityContextInterface(activity);
    aci.attach(this.sbbContext.getSbbLocalObject());

    // execute request on the activity
    activity.execute(httpRequest, request);
}

From source file:cn.geowind.takeout.verify.JsonRestApi.java

public String sendCall(String accountSid, String authToken, String appId, String to, String verifyCode)
        throws KeyManagementException, NoSuchAlgorithmException {
    String result = "";
    CcopHttpClient chc = new CcopHttpClient();
    DefaultHttpClient httpclient = chc.registerSSL("sandboxapp.cloopen.com", "TLS", 8883, "https");
    try {//ww  w  .  j a  va  2 s .  c  o  m
        // 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);

        StringBuffer sb = new StringBuffer();
        String url = sb.append(TEST_SMS_BASE_URL).append(SMS_VERSION).append("/Accounts/").append(accountSid)
                .append("/Calls").append("/VoiceVerify").append("?sig=").append(signature).toString();
        // HttpPost
        HttpPost httppost = new HttpPost(url);
        setHttpHeader(httppost);
        String src = accountSid + ":" + timestamp;
        String auth = eu.base64Encoder(src);
        httppost.setHeader("Authorization", auth);// base64(Id + ? +
        // )
        JSONObject obj = new JSONObject();
        obj.put("to", to);
        obj.put("appId", appId);
        obj.put("verifyCode", verifyCode);
        obj.put("playTimes", "3");
        String data = obj.toString();

        System.out.println("---------------------------- SendSMS for JSON begin----------------------------");
        System.out.println("data: " + data);

        BasicHttpEntity requestBody = new BasicHttpEntity();
        requestBody.setContent(new ByteArrayInputStream(data.getBytes("UTF-8")));
        requestBody.setContentLength(data.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:de.escidoc.bwelabs.deposit.DepositServiceSpec.java

private void setEntity(HttpPost post) {
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(this.getClass().getClassLoader().getResourceAsStream(CONTENT_EXAMPLE));
    post.setEntity(entity);//from   ww  w.  j  a va2s.  c o  m
}

From source file:cn.geowind.takeout.verify.JsonRestApi.java

/**
 * @brief ??/*from w w w . j a v a  2s.  co m*/
 * @param accountSid
 *            ?
 * @param authToken
 *            ?
 * @param appId
 *            id
 * @param to
 *            ?
 * @return HttpPost ???
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public String sendTemplateSMS(String accountSid, String authToken, String appId, String to, String code)
        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);

        StringBuffer sb = new StringBuffer();
        String url = sb.append(SMS_BASE_URL).append(SMS_VERSION).append("/Accounts/").append(accountSid)
                .append(SMS).append(TEMPLATE_SMS).append("?sig=").append(signature).toString();
        // HttpPost
        HttpPost httppost = new HttpPost(url);
        setHttpHeader(httppost);
        String src = accountSid + ":" + timestamp;
        String auth = eu.base64Encoder(src);
        httppost.setHeader("Authorization", auth);// base64(Id + ? +
        // )
        JSONObject obj = new JSONObject();
        obj.put("to", to);
        obj.put("appId", appId);
        obj.put("templateId", SMS_TEMPLATE_ID);
        JSONArray replace = new JSONArray();
        replace.put(code);
        obj.put("datas", replace);
        String data = obj.toString();

        System.out.println("---------------------------- SendSMS for JSON begin----------------------------");
        System.out.println("data: " + data);

        BasicHttpEntity requestBody = new BasicHttpEntity();
        requestBody.setContent(new ByteArrayInputStream(data.getBytes("UTF-8")));
        requestBody.setContentLength(data.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.lehealth.common.sdk.CCPRestSDK.java

/**
 * ???/*from   w  w w  . ja  va2s  .c  om*/
 * 
 * @param to
 *            ? ??????????100
 * @param templateId
 *            ? ?Id
 * @param datas
 *            ?? ???{??}
 * @return
 */
public JSONObject sendTemplateSMS(String to, String templateId, String[] datas, String domain, String appId,
        String sid, String token) {
    JSONObject errorInfo = this.accountValidate(domain, appId, sid, token);
    if (errorInfo != null) {
        return errorInfo;
    }

    if (StringUtils.isBlank(to) || StringUtils.isBlank(appId) || StringUtils.isBlank(templateId)) {
        throw new IllegalArgumentException("?:" + (StringUtils.isBlank(to) ? " ?? " : "")
                + (StringUtils.isBlank(templateId) ? " ?Id " : "") + "");
    }

    String timestamp = DateFormatUtils.format(new Date(), Constant.dateFormat_yyyymmddhhmmss);
    String acountName = sid;
    String sig = sid + token + timestamp;
    String acountType = "Accounts";
    String signature = DigestUtils.md5Hex(sig);
    String url = getBaseUrl(domain).append("/" + acountType + "/").append(acountName)
            .append("/" + TemplateSMS + "?sig=").append(signature).toString();

    String src = acountName + ":" + timestamp;
    String auth = Base64.encodeBase64String(src.getBytes());
    Map<String, String> header = new HashMap<String, String>();
    header.put("Accept", "application/json");
    header.put("Content-Type", "application/json;charset=utf-8");
    header.put("Authorization", auth);

    JSONObject json = new JSONObject();
    json.accumulate("appId", appId);
    json.accumulate("to", to);
    json.accumulate("templateId", templateId);
    if (datas != null) {
        JSONArray Jarray = new JSONArray();
        for (String s : datas) {
            Jarray.add(s);
        }
        json.accumulate("datas", Jarray);
    }
    String requestBody = json.toString();

    DefaultHttpClient httpclient = null;
    HttpPost postMethod = null;
    try {
        httpclient = new CcopHttpClient().registerSSL(domain, NumberUtils.toInt(SERVER_PORT), "TLS", "https");
        postMethod = new HttpPost(url);
        if (header != null && !header.isEmpty()) {
            for (Entry<String, String> e : header.entrySet()) {
                postMethod.setHeader(e.getKey(), e.getValue());
            }
        }
        postMethod.setConfig(PoolConnectionManager.requestConfig);
        BasicHttpEntity requestEntity = new BasicHttpEntity();
        requestEntity.setContent(new ByteArrayInputStream(requestBody.getBytes("UTF-8")));
        requestEntity.setContentLength(requestBody.getBytes("UTF-8").length);
        postMethod.setEntity(requestEntity);

        HttpResponse response = httpclient.execute(postMethod);

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            EntityUtils.consume(entity);
            return JSONObject.fromObject(result);
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
        if (httpclient != null) {
            httpclient.getConnectionManager().shutdown();
        }
    }
    return getMyError("999999", "");
}

From source file:dk.slott.super_volley.stacks.ExtHttpClientStack.java

private org.apache.http.HttpEntity convertEntityNewToOld(HttpEntity ent)
        throws IllegalStateException, IOException {
    final BasicHttpEntity ret = new BasicHttpEntity();
    if (ent != null) {
        ret.setContent(ent.getContent());
        ret.setContentLength(ent.getContentLength());
        Header h;/*from  w w w.  jav  a2  s  .co  m*/
        h = ent.getContentEncoding();
        if (h != null) {
            ret.setContentEncoding(convertheaderNewToOld(h));
        }
        h = ent.getContentType();
        if (h != null) {
            ret.setContentType(convertheaderNewToOld(h));
        }
    }
    return ret;
}

From source file:com.amazonaws.http.AmazonHttpClientTest.java

@Test
public void testRetryIOExceptionFromHandler() throws Exception {
    final IOException exception = new IOException("BOOM");

    HttpResponseHandler<AmazonWebServiceResponse<Object>> handler = EasyMock
            .createMock(HttpResponseHandler.class);

    EasyMock.expect(handler.needsConnectionLeftOpen()).andReturn(false).anyTimes();

    EasyMock.expect(handler.handle(EasyMock.<HttpResponse>anyObject())).andThrow(exception).times(4);

    EasyMock.replay(handler);/*from w  ww  .j  a  va  2  s . co  m*/

    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream(new byte[0]));

    BasicHttpResponse response = new BasicHttpResponse(new ProtocolVersion("http", 1, 1), 200, "OK");
    response.setEntity(entity);

    EasyMock.reset(httpClient);

    EasyMock.expect(httpClient.getConnectionManager()).andReturn(null).anyTimes();

    EasyMock.expect(httpClient.execute(EasyMock.<HttpUriRequest>anyObject(), EasyMock.<HttpContext>anyObject()))
            .andReturn(response).times(4);

    EasyMock.replay(httpClient);

    ExecutionContext context = new ExecutionContext();

    Request<?> request = new DefaultRequest<Object>(null, "testsvc");
    request.setEndpoint(java.net.URI.create("http://testsvc.region.amazonaws.com"));
    request.setContent(new java.io.ByteArrayInputStream(new byte[0]));

    try {

        client.execute(request, handler, null, context);
        Assert.fail("No exception when request repeatedly fails!");

    } catch (AmazonClientException e) {
        Assert.assertSame(exception, e.getCause());
    }

    // Verify that we called execute 4 times.
    EasyMock.verify(httpClient);
}

From source file:com.github.seratch.signedrequest4j.SignedRequestApacheHCImpl.java

@Override
public HttpResponse doRequest(String url, HttpMethod method, RequestBody body, String charset)
        throws IOException {

    HttpClient httpClient = new DefaultHttpClient();
    HttpUriRequest request = getRequest(method, url);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeoutMillis);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeoutMillis);
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT);
    httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, charset);

    for (String name : headersToOverwrite.keySet()) {
        request.setHeader(name, headersToOverwrite.get(name));
    }//from  ww  w.  j  a v a 2s  . co m

    String oAuthNonce = String.valueOf(new SecureRandom().nextLong());
    Long oAuthTimestamp = System.currentTimeMillis() / 1000;
    String signature = getSignature(url, method, oAuthNonce, oAuthTimestamp);
    String authorizationHeader = getAuthorizationHeader(signature, oAuthNonce, oAuthTimestamp);
    request.setHeader("Authorization", authorizationHeader);

    if (method == HttpMethod.POST) {
        HttpPost postRequest = (HttpPost) request;
        BasicHttpEntity entity = new BasicHttpEntity();
        entity.setContent(new ByteArrayInputStream(body.getBody()));
        entity.setContentType(body.getContentType());
        postRequest.setEntity(entity);
    } else if (method == HttpMethod.PUT) {
        HttpPut putRequest = (HttpPut) request;
        BasicHttpEntity entity = new BasicHttpEntity();
        entity.setContent(new ByteArrayInputStream(body.getBody()));
        entity.setContentType(body.getContentType());
        putRequest.setEntity(entity);
    }

    org.apache.http.HttpResponse apacheHCResponse = httpClient.execute(request);
    if (apacheHCResponse.getStatusLine().getStatusCode() >= 400) {
        HttpResponse httpResponse = toReturnValue(apacheHCResponse, charset);
        throw new HttpException(apacheHCResponse.getStatusLine().getReasonPhrase(), httpResponse);
    }
    return toReturnValue(apacheHCResponse, charset);
}

From source file:com.android.volley.toolbox.https.ExtHttpClientStack.java

private HttpEntity convertEntityNewToOld(HttpEntity ent) throws IllegalStateException, IOException {

    BasicHttpEntity ret = new BasicHttpEntity();
    if (ent != null) {
        ret.setContent(ent.getContent());
        ret.setContentLength(ent.getContentLength());
        Header h;//from ww  w  .j a  v  a 2s . c o  m
        h = (Header) ent.getContentEncoding();
        if (h != null) {
            ret.setContentEncoding(convertheaderNewToOld(h));
        }
        h = ent.getContentType();
        if (h != null) {
            ret.setContentType(convertheaderNewToOld(h));
        }
    }

    return ret;
}