Search in sources :

Example 41 with ByteArrayEntity

use of org.apache.http.entity.ByteArrayEntity in project web3sdk by FISCO-BCOS.

the class HttpService method send.

@Override
public <T extends Response> T send(Request request, Class<T> responseType) throws IOException {
    byte[] payload = objectMapper.writeValueAsBytes(request);
    HttpPost httpPost = new HttpPost(this.url);
    httpPost.setEntity(new ByteArrayEntity(payload));
    Header[] headers = buildHeaders();
    httpPost.setHeaders(headers);
    ResponseHandler<T> responseHandler = getResponseHandler(responseType);
    try {
        return httpClient.execute(httpPost, responseHandler);
    } finally {
        httpClient.close();
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader)

Example 42 with ByteArrayEntity

use of org.apache.http.entity.ByteArrayEntity in project janusgraph by JanusGraph.

the class RestElasticSearchClient method performRequest.

private Response performRequest(String method, String path, byte[] requestData) throws IOException {
    final HttpEntity entity = requestData != null ? new ByteArrayEntity(requestData, ContentType.APPLICATION_JSON) : null;
    final Response response = delegate.performRequest(method, path, Collections.emptyMap(), entity);
    if (response.getStatusLine().getStatusCode() >= 400) {
        throw new IOException("Error executing request: " + response.getStatusLine().getReasonPhrase());
    }
    return response;
}
Also used : RestBulkItemResponse(org.janusgraph.diskstorage.es.rest.RestBulkResponse.RestBulkItemResponse) Response(org.elasticsearch.client.Response) HttpEntity(org.apache.http.HttpEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) IOException(java.io.IOException)

Example 43 with ByteArrayEntity

use of org.apache.http.entity.ByteArrayEntity in project camel by apache.

the class HttpProducer method createRequestEntity.

/**
     * Creates a holder object for the data to send to the remote server.
     *
     * @param exchange the exchange with the IN message with data to send
     * @return the data holder
     * @throws CamelExchangeException is thrown if error creating RequestEntity
     */
protected HttpEntity createRequestEntity(Exchange exchange) throws CamelExchangeException {
    Message in = exchange.getIn();
    if (in.getBody() == null) {
        return null;
    }
    HttpEntity answer = in.getBody(HttpEntity.class);
    if (answer == null) {
        try {
            Object data = in.getBody();
            if (data != null) {
                String contentTypeString = ExchangeHelper.getContentType(exchange);
                ContentType contentType = null;
                //it removes "boundary" from Content-Type; I have to use contentType.create method.
                if (contentTypeString != null) {
                    // using ContentType.parser for charset
                    if (contentTypeString.indexOf("charset") > 0) {
                        contentType = ContentType.parse(contentTypeString);
                    } else {
                        contentType = ContentType.create(contentTypeString);
                    }
                }
                if (contentTypeString != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentTypeString)) {
                    if (!getEndpoint().getComponent().isAllowJavaSerializedObject()) {
                        throw new CamelExchangeException("Content-type " + org.apache.camel.http.common.HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT + " is not allowed", exchange);
                    }
                    // serialized java object
                    Serializable obj = in.getMandatoryBody(Serializable.class);
                    // write object to output stream
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    HttpHelper.writeObjectToStream(bos, obj);
                    ByteArrayEntity entity = new ByteArrayEntity(bos.toByteArray());
                    entity.setContentType(HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT);
                    IOHelper.close(bos);
                    answer = entity;
                } else if (data instanceof File || data instanceof GenericFile) {
                    // file based (could potentially also be a FTP file etc)
                    File file = in.getBody(File.class);
                    if (file != null) {
                        if (contentType != null) {
                            answer = new FileEntity(file, contentType);
                        } else {
                            answer = new FileEntity(file);
                        }
                    }
                } else if (data instanceof String) {
                    // be a bit careful with String as any type can most likely be converted to String
                    // so we only do an instanceof check and accept String if the body is really a String
                    // do not fallback to use the default charset as it can influence the request
                    // (for example application/x-www-form-urlencoded forms being sent)
                    String charset = IOHelper.getCharsetName(exchange, false);
                    if (charset == null && contentType != null) {
                        // okay try to get the charset from the content-type
                        Charset cs = contentType.getCharset();
                        if (cs != null) {
                            charset = cs.name();
                        }
                    }
                    StringEntity entity = new StringEntity((String) data, charset);
                    if (contentType != null) {
                        entity.setContentType(contentType.toString());
                    }
                    answer = entity;
                }
                // fallback as input stream
                if (answer == null) {
                    // force the body as an input stream since this is the fallback
                    InputStream is = in.getMandatoryBody(InputStream.class);
                    String length = in.getHeader(Exchange.CONTENT_LENGTH, String.class);
                    InputStreamEntity entity = null;
                    if (ObjectHelper.isEmpty(length)) {
                        entity = new InputStreamEntity(is, -1);
                    } else {
                        entity = new InputStreamEntity(is, Long.parseLong(length));
                    }
                    if (contentType != null) {
                        entity.setContentType(contentType.toString());
                    }
                    answer = entity;
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new CamelExchangeException("Error creating RequestEntity from message body", exchange, e);
        } catch (IOException e) {
            throw new CamelExchangeException("Error serializing message body", exchange, e);
        }
    }
    return answer;
}
Also used : CamelExchangeException(org.apache.camel.CamelExchangeException) Serializable(java.io.Serializable) FileEntity(org.apache.http.entity.FileEntity) Message(org.apache.camel.Message) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) InputStream(java.io.InputStream) Charset(java.nio.charset.Charset) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) InputStreamEntity(org.apache.http.entity.InputStreamEntity) StringEntity(org.apache.http.entity.StringEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File) GenericFile(org.apache.camel.component.file.GenericFile)

Example 44 with ByteArrayEntity

use of org.apache.http.entity.ByteArrayEntity in project cdap-ingest by caskdata.

the class RestStreamWriter method write.

@Override
public ListenableFuture<Void> write(ByteBuffer buffer, Map<String, String> headers) throws IllegalArgumentException {
    Preconditions.checkNotNull(buffer, "ByteBuffer parameter is null.");
    HttpEntity content;
    if (buffer.hasArray()) {
        content = new ByteArrayEntity(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining());
    } else {
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        content = new ByteArrayEntity(bytes);
    }
    return write(content, headers);
}
Also used : HttpEntity(org.apache.http.HttpEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity)

Example 45 with ByteArrayEntity

use of org.apache.http.entity.ByteArrayEntity in project jersey by jersey.

the class MessageBodyReaderTest method testDefaultContentTypeForReader.

/**
     * Test whether the default {@link MediaType} ({@value MediaType#APPLICATION_OCTET_STREAM}) is passed to a reader if no
     * {@value HttpHeaders#CONTENT_TYPE} value is provided in a request.
     */
@Test
public void testDefaultContentTypeForReader() throws Exception {
    final HttpPost httpPost = new HttpPost(UriBuilder.fromUri(getBaseUri()).path("resource/plain").build());
    httpPost.setEntity(new ByteArrayEntity("value".getBytes()));
    httpPost.removeHeaders("Content-Type");
    final HttpClient httpClient = HttpClientBuilder.create().build();
    final HttpResponse response = httpClient.execute(httpPost);
    assertEquals(200, response.getStatusLine().getStatusCode());
    assertEquals("value;null", ReaderWriter.readFromAsString(response.getEntity().getContent(), null));
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Aggregations

ByteArrayEntity (org.apache.http.entity.ByteArrayEntity)78 HttpEntity (org.apache.http.HttpEntity)28 HttpPost (org.apache.http.client.methods.HttpPost)24 HttpResponse (org.apache.http.HttpResponse)20 IOException (java.io.IOException)17 ByteArrayOutputStream (java.io.ByteArrayOutputStream)16 JSONObject (org.json.JSONObject)11 Test (org.junit.Test)10 HttpClient (org.apache.http.client.HttpClient)9 InputStream (java.io.InputStream)7 JSONArray (org.json.JSONArray)7 URISyntaxException (java.net.URISyntaxException)5 Header (org.apache.http.Header)5 AbstractHttpEntity (org.apache.http.entity.AbstractHttpEntity)5 ContentType (org.apache.http.entity.ContentType)5 BytesRef (org.apache.lucene.util.BytesRef)5 DocWriteRequest (org.elasticsearch.action.DocWriteRequest)5 BulkRequest (org.elasticsearch.action.bulk.BulkRequest)5 DeleteRequest (org.elasticsearch.action.delete.DeleteRequest)5 GetRequest (org.elasticsearch.action.get.GetRequest)5