Search in sources :

Example 21 with InputStreamEntity

use of org.apache.http.entity.InputStreamEntity in project hbase by apache.

the class Client method post.

/**
   * Send a POST request
   * @param cluster the cluster definition
   * @param path the path or URI
   * @param headers the HTTP headers to include, <tt>Content-Type</tt> must be
   * supplied
   * @param content the content bytes
   * @return a Response object with response detail
   * @throws IOException
   */
public Response post(Cluster cluster, String path, Header[] headers, byte[] content) throws IOException {
    HttpPost method = new HttpPost(path);
    try {
        method.setEntity(new InputStreamEntity(new ByteArrayInputStream(content), content.length));
        HttpResponse resp = execute(cluster, method, headers, path);
        headers = resp.getAllHeaders();
        content = getResponseBody(resp);
        return new Response(resp.getStatusLine().getStatusCode(), headers, content);
    } finally {
        method.releaseConnection();
    }
}
Also used : HttpResponse(org.apache.http.HttpResponse) HttpPost(org.apache.http.client.methods.HttpPost) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpResponse(org.apache.http.HttpResponse) InputStreamEntity(org.apache.http.entity.InputStreamEntity)

Example 22 with InputStreamEntity

use of org.apache.http.entity.InputStreamEntity in project elasticsearch by elastic.

the class RequestLoggerTests method testTraceRequest.

public void testTraceRequest() throws IOException, URISyntaxException {
    HttpHost host = new HttpHost("localhost", 9200, randomBoolean() ? "http" : "https");
    String expectedEndpoint = "/index/type/_api";
    URI uri;
    if (randomBoolean()) {
        uri = new URI(expectedEndpoint);
    } else {
        uri = new URI("index/type/_api");
    }
    HttpUriRequest request = randomHttpRequest(uri);
    String expected = "curl -iX " + request.getMethod() + " '" + host + expectedEndpoint + "'";
    boolean hasBody = request instanceof HttpEntityEnclosingRequest && randomBoolean();
    String requestBody = "{ \"field\": \"value\" }";
    if (hasBody) {
        expected += " -d '" + requestBody + "'";
        HttpEntityEnclosingRequest enclosingRequest = (HttpEntityEnclosingRequest) request;
        HttpEntity entity;
        switch(randomIntBetween(0, 4)) {
            case 0:
                entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
                break;
            case 1:
                entity = new InputStreamEntity(new ByteArrayInputStream(requestBody.getBytes(StandardCharsets.UTF_8)), ContentType.APPLICATION_JSON);
                break;
            case 2:
                entity = new NStringEntity(requestBody, ContentType.APPLICATION_JSON);
                break;
            case 3:
                entity = new NByteArrayEntity(requestBody.getBytes(StandardCharsets.UTF_8), ContentType.APPLICATION_JSON);
                break;
            case 4:
                // Evil entity without a charset
                entity = new StringEntity(requestBody, ContentType.create("application/json", (Charset) null));
                break;
            default:
                throw new UnsupportedOperationException();
        }
        enclosingRequest.setEntity(entity);
    }
    String traceRequest = RequestLogger.buildTraceRequest(request, host);
    assertThat(traceRequest, equalTo(expected));
    if (hasBody) {
        //check that the body is still readable as most entities are not repeatable
        String body = EntityUtils.toString(((HttpEntityEnclosingRequest) request).getEntity(), StandardCharsets.UTF_8);
        assertThat(body, equalTo(requestBody));
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpEntity(org.apache.http.HttpEntity) URI(java.net.URI) InputStreamEntity(org.apache.http.entity.InputStreamEntity) NStringEntity(org.apache.http.nio.entity.NStringEntity) StringEntity(org.apache.http.entity.StringEntity) NStringEntity(org.apache.http.nio.entity.NStringEntity) NByteArrayEntity(org.apache.http.nio.entity.NByteArrayEntity) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpHost(org.apache.http.HttpHost) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest)

Example 23 with InputStreamEntity

use of org.apache.http.entity.InputStreamEntity in project elasticsearch by elastic.

the class RequestLoggerTests method testTraceResponse.

public void testTraceResponse() throws IOException {
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int statusCode = randomIntBetween(200, 599);
    String reasonPhrase = "REASON";
    BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase);
    String expected = "# " + statusLine.toString();
    BasicHttpResponse httpResponse = new BasicHttpResponse(statusLine);
    int numHeaders = randomIntBetween(0, 3);
    for (int i = 0; i < numHeaders; i++) {
        httpResponse.setHeader("header" + i, "value");
        expected += "\n# header" + i + ": value";
    }
    expected += "\n#";
    boolean hasBody = getRandom().nextBoolean();
    String responseBody = "{\n  \"field\": \"value\"\n}";
    if (hasBody) {
        expected += "\n# {";
        expected += "\n#   \"field\": \"value\"";
        expected += "\n# }";
        HttpEntity entity;
        switch(randomIntBetween(0, 2)) {
            case 0:
                entity = new StringEntity(responseBody, ContentType.APPLICATION_JSON);
                break;
            case 1:
                //test a non repeatable entity
                entity = new InputStreamEntity(new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8)), ContentType.APPLICATION_JSON);
                break;
            case 2:
                // Evil entity without a charset
                entity = new StringEntity(responseBody, ContentType.create("application/json", (Charset) null));
                break;
            default:
                throw new UnsupportedOperationException();
        }
        httpResponse.setEntity(entity);
    }
    String traceResponse = RequestLogger.buildTraceResponse(httpResponse);
    assertThat(traceResponse, equalTo(expected));
    if (hasBody) {
        //check that the body is still readable as most entities are not repeatable
        String body = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
        assertThat(body, equalTo(responseBody));
    }
}
Also used : NStringEntity(org.apache.http.nio.entity.NStringEntity) StringEntity(org.apache.http.entity.StringEntity) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpEntity(org.apache.http.HttpEntity) ByteArrayInputStream(java.io.ByteArrayInputStream) ProtocolVersion(org.apache.http.ProtocolVersion) BasicStatusLine(org.apache.http.message.BasicStatusLine) InputStreamEntity(org.apache.http.entity.InputStreamEntity)

Example 24 with InputStreamEntity

use of org.apache.http.entity.InputStreamEntity in project elasticsearch by elastic.

the class RemoteScrollableHitSourceTests method sourceWithMockedRemoteCall.

/**
     * Creates a hit source that doesn't make the remote request and instead returns data from some files. Also requests are always returned
     * synchronously rather than asynchronously.
     */
@SuppressWarnings("unchecked")
private RemoteScrollableHitSource sourceWithMockedRemoteCall(boolean mockRemoteVersion, ContentType contentType, String... paths) throws Exception {
    URL[] resources = new URL[paths.length];
    for (int i = 0; i < paths.length; i++) {
        resources[i] = Thread.currentThread().getContextClassLoader().getResource("responses/" + paths[i].replace("fail:", ""));
        if (resources[i] == null) {
            throw new IllegalArgumentException("Couldn't find [" + paths[i] + "]");
        }
    }
    CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class);
    when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class))).thenAnswer(new Answer<Future<HttpResponse>>() {

        int responseCount = 0;

        @Override
        public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable {
            // Throw away the current thread context to simulate running async httpclient's thread pool
            threadPool.getThreadContext().stashContext();
            HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock.getArguments()[0];
            FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock.getArguments()[3];
            HttpEntityEnclosingRequest request = (HttpEntityEnclosingRequest) requestProducer.generateRequest();
            URL resource = resources[responseCount];
            String path = paths[responseCount++];
            ProtocolVersion protocolVersion = new ProtocolVersion("http", 1, 1);
            if (path.startsWith("fail:")) {
                String body = Streams.copyToString(new InputStreamReader(request.getEntity().getContent(), StandardCharsets.UTF_8));
                if (path.equals("fail:rejection.json")) {
                    StatusLine statusLine = new BasicStatusLine(protocolVersion, RestStatus.TOO_MANY_REQUESTS.getStatus(), "");
                    BasicHttpResponse httpResponse = new BasicHttpResponse(statusLine);
                    futureCallback.completed(httpResponse);
                } else {
                    futureCallback.failed(new RuntimeException(body));
                }
            } else {
                StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "");
                HttpResponse httpResponse = new BasicHttpResponse(statusLine);
                httpResponse.setEntity(new InputStreamEntity(FileSystemUtils.openFileURLStream(resource), contentType));
                futureCallback.completed(httpResponse);
            }
            return null;
        }
    });
    return sourceWithMockedClient(mockRemoteVersion, httpClient);
}
Also used : InputStreamReader(java.io.InputStreamReader) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) HttpAsyncResponseConsumer(org.apache.http.nio.protocol.HttpAsyncResponseConsumer) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) Matchers.containsString(org.hamcrest.Matchers.containsString) ProtocolVersion(org.apache.http.ProtocolVersion) URL(java.net.URL) BasicStatusLine(org.apache.http.message.BasicStatusLine) InputStreamEntity(org.apache.http.entity.InputStreamEntity) StatusLine(org.apache.http.StatusLine) BasicStatusLine(org.apache.http.message.BasicStatusLine) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpAsyncRequestProducer(org.apache.http.nio.protocol.HttpAsyncRequestProducer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) CloseableHttpAsyncClient(org.apache.http.impl.nio.client.CloseableHttpAsyncClient) ScheduledFuture(java.util.concurrent.ScheduledFuture) Future(java.util.concurrent.Future) FutureCallback(org.apache.http.concurrent.FutureCallback)

Example 25 with InputStreamEntity

use of org.apache.http.entity.InputStreamEntity in project Notes by lguipeng.

the class TEvernoteHttpClient method flush.

@Deprecated
public void flush() throws TTransportException {
    long timer = System.currentTimeMillis();
    HttpEntity httpEntity;
    // Extract request and reset buffer
    try {
        // Prepare http post request
        HttpPost request = new HttpPost(url.toExternalForm());
        this.request = request;
        request.addHeader("Content-Type", "application/x-thrift");
        request.addHeader("Cache-Control", "no-transform");
        if (customHeaders != null) {
            for (Map.Entry<String, String> header : customHeaders.entrySet()) {
                request.addHeader(header.getKey(), header.getValue());
            }
        }
        InputStreamEntity entity = new InputStreamEntity(requestBuffer.getInputStream(), requestBuffer.getBytesWritten());
        request.setEntity(entity);
        request.addHeader("Accept", "application/x-thrift");
        request.addHeader("User-Agent", userAgent == null ? "Java/THttpClient" : userAgent);
        request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        DefaultHttpClient dHTTP = getHTTPClient();
        //noinspection ConstantConditions
        HttpResponse response = dHTTP.execute(request);
        httpEntity = response.getEntity();
        int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode != 200) {
            if (httpEntity != null) {
                httpEntity.consumeContent();
            }
            throw new TTransportException("HTTP Response code: " + responseCode);
        }
        // Read the responses
        requestBuffer.reset();
        inputStream = response.getEntity().getContent();
    } catch (Exception ex) {
        throw new TTransportException(ex);
    } finally {
        try {
            requestBuffer.reset();
        } catch (IOException ignored) {
        }
        this.request = null;
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) TTransportException(com.evernote.thrift.transport.TTransportException) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) IOException(java.io.IOException) TTransportException(com.evernote.thrift.transport.TTransportException) InputStreamEntity(org.apache.http.entity.InputStreamEntity) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

InputStreamEntity (org.apache.http.entity.InputStreamEntity)41 ByteArrayInputStream (java.io.ByteArrayInputStream)15 HttpPost (org.apache.http.client.methods.HttpPost)14 HttpResponse (org.apache.http.HttpResponse)12 InputStream (java.io.InputStream)10 Test (org.junit.Test)10 HttpEntity (org.apache.http.HttpEntity)8 IOException (java.io.IOException)7 HttpPut (org.apache.http.client.methods.HttpPut)7 Map (java.util.Map)4 HttpEntityEnclosingRequest (org.apache.http.HttpEntityEnclosingRequest)4 HttpClient (org.apache.http.client.HttpClient)4 StringEntity (org.apache.http.entity.StringEntity)4 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)4 URISyntaxException (java.net.URISyntaxException)3 HashMap (java.util.HashMap)3 Header (org.apache.http.Header)3 ProtocolVersion (org.apache.http.ProtocolVersion)3 HttpGet (org.apache.http.client.methods.HttpGet)3 BasicHttpEntityEnclosingRequest (org.apache.http.message.BasicHttpEntityEnclosingRequest)3