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

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

Introduction

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

Prototype

public BasicHttpEntity() 

Source Link

Usage

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

@Test
public void testB_C1_FC_IB__C2_FC_IB() throws IOException {
    String data = "0123456789";
    BasicHttpEntity basic;// w ww. j  a va  2s. c o m
    PartiallyRepeatableHttpEntity replay;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(data.getBytes("UTF-8")));
    replay = new PartiallyRepeatableHttpEntity(basic, 20);

    String output;

    output = blockRead(replay.getContent(), UTF8, -1, 3);
    assertThat(output, is(data));

    output = blockRead(replay.getContent(), UTF8, -1, 3);
    assertThat(output, is(data));
}

From source file:com.aerofs.baseline.http.TestHttpRequestHandler.java

@Test
public void shouldSuccessfullyPostAndReceiveResponseAfterMakingUnsuccessfulPost() throws Exception {
    // unsuccessful
    // how does this test work, you ask?
    // well, there's only one request processing
    // thread on the server so if that thread locks up waiting
    // for bytes that never come, even if the stream is closed
    // then the *second* request will time out.
    try {/*  ww  w.ja v  a2 s.co  m*/
        HttpPost post0 = new HttpPost(
                ServiceConfiguration.SERVICE_URL + "/" + Resources.BASIC_RESOURCE + "/data1");
        post0.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN);
        BasicHttpEntity basic = new BasicHttpEntity();
        basic.setChunked(true);
        basic.setContentLength(-1);
        basic.setContent(new InputStream() {

            private int counter = 0;

            @Override
            public int read() throws IOException {
                if (counter < (3 * 1024 * 1024)) {
                    counter++;
                    return 'a';
                } else {
                    throw new IOException("read failed");
                }
            }
        });
        post0.setEntity(basic);

        Future<HttpResponse> future0 = client.getClient().execute(post0, null);
        future0.get();
    } catch (Exception e) {
        // noop
    }

    // successful
    HttpPost post = new HttpPost(ServiceConfiguration.SERVICE_URL + "/" + Resources.BASIC_RESOURCE + "/data1");
    post.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN);
    post.setEntity(HttpUtils.writeStringToEntity("data2"));

    Future<HttpResponse> future = client.getClient().execute(post, null);
    HttpResponse response = future.get(10, TimeUnit.SECONDS);

    assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_OK));
    assertThat(HttpUtils.readStreamToString(response.getEntity().getContent()), equalTo("data1-data2"));
}

From source file:ai.eve.volley.stack.HurlStack.java

/**
 * Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
 * @return an HttpEntity populated with data from <code>connection</code>.
 *//*from  w w w  . j  av a2  s.  co m*/
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}

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

@Test
public void testB_C1_FC_IB__C2_FC_IB() throws IOException {
    String data = "0123456789";
    BasicHttpEntity basic;//  ww w .  j  a  v a 2 s  . c  o m
    CappedBufferHttpEntity replay;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(data.getBytes("UTF-8")));
    replay = new CappedBufferHttpEntity(basic, 20);

    String output;

    output = blockRead(replay.getContent(), UTF8, -1, 3);
    assertThat(output, is(data));

    output = blockRead(replay.getContent(), UTF8, -1, 3);
    assertThat(output, is(data));
}

From source file:com.yangcong345.android.phone.manager.OkHttpStack.java

/**
 * Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
 *
 * @return an HttpEntity populated with data from <code>connection</code>.
 */// w  w  w  .j av  a2  s .co  m
private static HttpEntity entityFromOkHttp(Response okResponse) {
    ResponseBody rb = okResponse.body();

    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream = rb.byteStream();
    entity.setContent(inputStream);
    entity.setContentLength(rb.contentLength());
    entity.setContentType(rb.contentType().type());
    return entity;
}

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

/**
* @brief               ??//from  w  w  w  .  ja v  a  2  s . c o m
* @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: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  www  . j  ava 2s. c  o 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.baasbox.android.net.OkClient.java

private HttpEntity asEntity(Response resp) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream = resp.body().byteStream();
    entity.setContent(inputStream);/*  ww w. j  a v  a  2 s.  c o  m*/
    entity.setContentLength(resp.body().contentLength());
    String ctnt = resp.body().contentType().toString();
    entity.setContentType(ctnt);
    return entity;
}

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);/*ww  w. j  a va 2s.com*/

    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:com.nexmo.client.voice.endpoints.ListCallsMethodTest.java

@Test
public void parseResponse() throws Exception {
    HttpResponse stubResponse = new BasicHttpResponse(
            new BasicStatusLine(new ProtocolVersion("1.1", 1, 1), 200, "OK"));

    String json = "{\n" + "  \"page_size\": 10,\n" + "  \"record_index\": 0,\n" + "  \"count\": 2,\n"
            + "  \"_embedded\": {\n" + "    \"calls\": [\n" + "      {\n"
            + "        \"uuid\": \"93137ee3-580e-45f7-a61a-e0b5716000ef\",\n"
            + "        \"status\": \"completed\",\n" + "        \"direction\": \"outbound\",\n"
            + "        \"rate\": \"0.02400000\",\n" + "        \"price\": \"0.00280000\",\n"
            + "        \"duration\": \"7\",\n" + "        \"network\": \"23410\",\n"
            + "        \"conversation_uuid\": \"aa17bd11-c895-4225-840d-30dc38c31e50\",\n"
            + "        \"start_time\": \"2017-01-13T13:55:02.000Z\",\n"
            + "        \"end_time\": \"2017-01-13T13:55:09.000Z\",\n" + "        \"to\": {\n"
            + "          \"type\": \"phone\",\n" + "          \"number\": \"447700900104\"\n" + "        },\n"
            + "        \"from\": {\n" + "          \"type\": \"phone\",\n"
            + "          \"number\": \"447700900105\"\n" + "        },\n" + "        \"_links\": {\n"
            + "          \"self\": {\n"
            + "            \"href\": \"/v1/calls/93137ee3-580e-45f7-a61a-e0b5716000ef\"\n" + "          }\n"
            + "        }\n" + "      },\n" + "      {\n"
            + "        \"uuid\": \"105e02df-940a-466c-b28b-51ae015a9166\",\n"
            + "        \"status\": \"completed\",\n" + "        \"direction\": \"outbound\",\n"
            + "        \"rate\": \"0.02400000\",\n" + "        \"price\": \"0.00280000\",\n"
            + "        \"duration\": \"7\",\n" + "        \"network\": \"23410\",\n"
            + "        \"conversation_uuid\": \"1467b438-f5a8-4937-9a65-e1f946a2f664\",\n"
            + "        \"start_time\": \"2017-01-11T15:03:46.000Z\",\n"
            + "        \"end_time\": \"2017-01-11T15:03:53.000Z\",\n" + "        \"to\": {\n"
            + "          \"type\": \"phone\",\n" + "          \"number\": \"447700900104\"\n" + "        },\n"
            + "        \"from\": {\n" + "          \"type\": \"phone\",\n"
            + "          \"number\": \"447700900105\"\n" + "        },\n" + "        \"_links\": {\n"
            + "          \"self\": {\n"
            + "            \"href\": \"/v1/calls/105e02df-940a-466c-b28b-51ae015a9166\"\n" + "          }\n"
            + "        }\n" + "      }\n" + "    ]\n" + "  },\n" + "  \"_links\": {\n" + "    \"self\": {\n"
            + "      \"href\": \"/v1/calls?page_size=10&record_index=0\"\n" + "    },\n" + "    \"first\": {\n"
            + "      \"href\": \"/v1/calls?page_size=10\"\n" + "    },\n" + "    \"last\": {\n"
            + "      \"href\": \"/v1/calls?page_size=10\"\n" + "    }\n" + "  }\n" + "}\n";
    InputStream jsonStream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(jsonStream);/*from   w w w  .  j  av a  2 s. c o  m*/
    stubResponse.setEntity(entity);

    CallInfoPage page = method.parseResponse(stubResponse);
    assertEquals(2, page.getCount());
    assertEquals(2, page.getEmbedded().getCallInfos().length);
    assertEquals("/v1/calls?page_size=10", page.getLinks().getFirst().getHref());
    assertEquals("/v1/calls?page_size=10", page.getLinks().getLast().getHref());
}