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:cn.garymb.wechatmoments.common.OkHttpStack.java

@SuppressWarnings("deprecation")
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;/*  www. ja v  a 2  s .c o  m*/
    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.docx4j.services.client.ConverterHttp.java

/**
 * Convert InputStream fromFormat to toFormat, streaming result to OutputStream os.
 * //from   w  w w.j a v a 2s .  c o  m
 * fromFormat supported: DOC, DOCX
 * 
 * toFormat supported: PDF
 * 
 * Note this uses a non-repeatable request entity, so it may not be suitable
 * (depending on the endpoint config).
 * 
 * @param instream
 * @param fromFormat
 * @param toFormat
 * @param os
 * @throws IOException
 * @throws ConversionException
 */
public void convert(InputStream instream, Format fromFormat, Format toFormat, OutputStream os)
        throws IOException, ConversionException {

    checkParameters(fromFormat, toFormat);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = getUrlForFormat(toFormat);

        BasicHttpEntity reqEntity = new BasicHttpEntity();
        reqEntity.setContentType(map(fromFormat).getMimeType()); // messy that API is different to FileEntity
        reqEntity.setContent(instream);

        httppost.setEntity(reqEntity);

        execute(httpclient, httppost, os);
    } finally {
        httpclient.close();
    }

}

From source file:com.aerofs.baseline.json.TestJSONHandling.java

@Test
public void shouldReceiveErrorOnMakingPostWithInvalidJsonObject()
        throws ExecutionException, InterruptedException, JsonProcessingException {
    // noinspection ConstantConditions
    String serialized = mapper.writeValueAsString(new JsonObject(null, "allen")); // yes; I know I'm using 'null'
    ByteArrayInputStream contentInputStream = new ByteArrayInputStream(serialized.getBytes(Charsets.US_ASCII));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(contentInputStream);

    HttpPost post = new HttpPost(ServiceConfiguration.SERVICE_URL + "/consumer");
    post.setHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON));
    post.setEntity(entity);/* w  w  w. j  av a2s  .  co  m*/

    Future<HttpResponse> future = client.getClient().execute(post, null);
    HttpResponse response = future.get();
    assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_BAD_REQUEST));
}

From source file:org.sahli.asciidoc.confluence.publisher.client.http.HttpRequestFactory.java

HttpPut updatePageRequest(String contentId, String ancestorId, String title, String content, int newVersion) {
    assertMandatoryParameter(isNotBlank(contentId), "contentId");
    assertMandatoryParameter(isNotBlank(ancestorId), "ancestorId");
    assertMandatoryParameter(isNotBlank(title), "title");

    PagePayload pagePayload = pagePayloadBuilder().ancestorId(ancestorId).title(title).content(content)
            .version(newVersion).build();

    String jsonPayload = toJsonString(pagePayload);
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream(jsonPayload.getBytes()));

    HttpPut updatePageRequest = new HttpPut(this.confluenceRestApiEndpoint + "/content/" + contentId);
    updatePageRequest.setEntity(entity);
    updatePageRequest.addHeader(APPLICATION_JSON_UTF8_HEADER);

    return updatePageRequest;
}

From source file:com.restqueue.framework.client.messageupdate.BasicMessageUpdater.java

/**
 * This method updates the message given the headers and body that you want to update have been set.
 * @return The result of the operation giving you access to the http response code and error information
 *///from  ww  w.j av a  2s .co  m
public ConditionalPutResult updateMessage() {
    Object messageBody = null;
    if (stringBody == null && objectBody == null) {
        throw new IllegalArgumentException("String body and Object body cannot both be null.");
    } else {
        if (stringBody != null) {
            messageBody = stringBody;
        }
        if (objectBody != null) {
            messageBody = objectBody;
        }
    }

    if (urlLocation == null) {
        throw new IllegalArgumentException("The Channel Endpoint must be set.");
    }
    if (eTag == null) {
        throw new ChannelClientException("Must set the eTag value to update a message.",
                ChannelClientException.ExceptionType.MISSING_DATA);
    }

    if (messageBody instanceof String && asType == null) {
        throw new IllegalArgumentException("The type must be set when using a String body.");
    }

    final HttpPut httpPut = new HttpPut(urlLocation);

    try {
        if (messageBody instanceof String) {
            httpPut.setEntity(new StringEntity((String) messageBody));
            httpPut.setHeader(HttpHeaders.CONTENT_TYPE, asType.toString());
        } else {
            httpPut.setEntity(
                    new StringEntity(new Serializer().toType(messageBody, MediaType.APPLICATION_JSON)));
            httpPut.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
        }
    } catch (UnsupportedEncodingException e) {
        httpPut.setEntity(new BasicHttpEntity());
    }

    for (Map.Entry<CustomHeaders, List<String>> entry : headerMap.entrySet()) {
        for (String headerValue : entry.getValue()) {
            httpPut.addHeader(entry.getKey().getName(), headerValue);
        }
    }

    httpPut.addHeader(CustomHeaders.IF_MATCH.getName(), eTag);

    DefaultHttpClient client = new DefaultHttpClient(params);
    try {
        final HttpResponse response = client.execute(httpPut);
        return new ResultsFactory().conditionalPutResultFromHttpPutResponse(response);
    } catch (HttpHostConnectException e) {
        throw new ChannelClientException(
                "Exception connecting to server. "
                        + "Ensure server is running and configured using the right ip address and port.",
                e, ChannelClientException.ExceptionType.CONNECTION);
    } catch (ClientProtocolException e) {
        throw new ChannelClientException("Exception communicating with server.", e,
                ChannelClientException.ExceptionType.TRANSPORT_PROTOCOL);
    } catch (Exception e) {
        throw new ChannelClientException("Unknown exception occurred when trying to update the message:", e,
                ChannelClientException.ExceptionType.UNKNOWN);
    }

}

From source file:com.gistlabs.mechanize.PageRequest.java

public HttpResponse consume(final HttpClient client, final HttpRequestBase request) throws Exception {
    if (!wasExecuted) {
        this.client = client;
        this.request = request;

        if (!request.getMethod().equalsIgnoreCase(httpMethod))
            throw new IllegalArgumentException(
                    String.format("Expected %s, but was %s", httpMethod, request.getMethod()));

        if (request.getURI().toString().equals(uri)) {
            HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK");
            BasicHttpEntity entity = new BasicHttpEntity();
            if (contentLocation != null)
                response.addHeader(new BasicHeader("Content-Location", contentLocation));
            entity.setContentEncoding(charset);
            entity.setContentType(this.contentType);
            entity.setContent(this.body);
            response.setEntity(new BufferedHttpEntity(entity));

            assertParameters(request);//from   w w w .ja  v a  2  s  .c  o  m
            assertHeaders(request);

            this.wasExecuted = true;
            return response;
        } else {
            assertEquals("URI of the next PageRequest does not match", uri, request.getURI().toString());
            return null;
        }
    } else
        throw new UnsupportedOperationException("Request already executed");
}

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

@Test
public void testB__C1_FC_OB() throws IOException {
    String data = "0123456789";
    BasicHttpEntity basic;//  ww  w .java  2  s. co m
    PartiallyRepeatableHttpEntity replay;

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

    String output;

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

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

@Test
public void testB__C1_FC_OB() throws IOException {
    String data = "0123456789";
    BasicHttpEntity basic;//from  w  w  w  .  ja v  a 2s. co  m
    CappedBufferHttpEntity replay;

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

    String output;

    try {
        output = blockRead(replay.getContent(), UTF8, -1, 3);
        fail("expected IOException");
    } catch (IOException e) {
        // expected
    }
}