Search in sources :

Example 26 with BasicClassicHttpResponse

use of org.apache.hc.core5.http.message.BasicClassicHttpResponse in project dialogue by palantir.

the class InactivityValidationAwareConnectionKeepAliveStrategyTest method testKeepAliveHeaderWithZeroTimeout.

@Test
void testKeepAliveHeaderWithZeroTimeout() {
    InactivityValidationAwareConnectionKeepAliveStrategy strategy = new InactivityValidationAwareConnectionKeepAliveStrategy(manager, "name");
    BasicClassicHttpResponse response = new BasicClassicHttpResponse(200);
    response.addHeader("Keep-Alive", "timeout=0");
    TimeValue value = strategy.getKeepAliveDuration(response, CONTEXT);
    assertThat(value).isEqualTo(CONTEXT.getRequestConfig().getConnectionKeepAlive());
    verify(manager).setValidateAfterInactivity(eq(INITIAL_TIMEOUT));
}
Also used : TimeValue(org.apache.hc.core5.util.TimeValue) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) Test(org.junit.jupiter.api.Test)

Example 27 with BasicClassicHttpResponse

use of org.apache.hc.core5.http.message.BasicClassicHttpResponse in project mercury by yellow013.

the class ClientInterceptors method main.

public static void main(final String[] args) throws Exception {
    try (final CloseableHttpClient httpclient = HttpClients.custom().addRequestInterceptorFirst(new HttpRequestInterceptor() {

        private final AtomicLong count = new AtomicLong(0);

        @Override
        public void process(final HttpRequest request, final EntityDetails entity, final HttpContext context) throws HttpException, IOException {
            request.setHeader("request-id", Long.toString(count.incrementAndGet()));
        }
    }).addExecInterceptorAfter(ChainElement.PROTOCOL.name(), "custom", new ExecChainHandler() {

        @Override
        public ClassicHttpResponse execute(final ClassicHttpRequest request, final ExecChain.Scope scope, final ExecChain chain) throws IOException, HttpException {
            final Header idHeader = request.getFirstHeader("request-id");
            if (idHeader != null && "13".equalsIgnoreCase(idHeader.getValue())) {
                final ClassicHttpResponse response = new BasicClassicHttpResponse(HttpStatus.SC_NOT_FOUND, "Oppsie");
                response.setEntity(new StringEntity("bad luck", ContentType.TEXT_PLAIN));
                return response;
            } else {
                return chain.proceed(request, scope);
            }
        }
    }).build()) {
        for (int i = 0; i < 20; i++) {
            final HttpGet httpget = new HttpGet("http://httpbin.org/get");
            System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
            try (final CloseableHttpResponse response = httpclient.execute(httpget)) {
                System.out.println("----------------------------------------");
                System.out.println(response.getCode() + " " + response.getReasonPhrase());
                System.out.println(EntityUtils.toString(response.getEntity()));
            }
        }
    }
}
Also used : ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) HttpGet(org.apache.hc.client5.http.classic.methods.HttpGet) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) IOException(java.io.IOException) StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) AtomicLong(java.util.concurrent.atomic.AtomicLong) ExecChainHandler(org.apache.hc.client5.http.classic.ExecChainHandler) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) Header(org.apache.hc.core5.http.Header) ExecChain(org.apache.hc.client5.http.classic.ExecChain) HttpRequestInterceptor(org.apache.hc.core5.http.HttpRequestInterceptor) EntityDetails(org.apache.hc.core5.http.EntityDetails) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) HttpException(org.apache.hc.core5.http.HttpException) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse)

Example 28 with BasicClassicHttpResponse

use of org.apache.hc.core5.http.message.BasicClassicHttpResponse in project LinkAgent by shulieTech.

the class HttpClientv5MethodInterceptor method beforeLast.

@Override
public void beforeLast(Advice advice) throws ProcessControlException {
    Object[] args = advice.getParameterArray();
    // HttpHost
    HttpHost httpHost = (HttpHost) args[0];
    final ClassicHttpRequest request = (ClassicHttpRequest) args[1];
    if (httpHost == null) {
        return;
    }
    String host = httpHost.getHostName();
    int port = httpHost.getPort();
    String path = httpHost.getHostName();
    if (request instanceof HttpRequest) {
        path = ((HttpRequest) request).getPath();
    }
    // 判断是否在白名单中
    String url = getService(httpHost.getSchemeName(), host, port, path);
    MatchConfig config = ClusterTestUtils.httpClusterTest(url);
    Header[] headers = request.getHeaders(PradarService.PRADAR_WHITE_LIST_CHECK);
    if (headers != null && headers.length > 0) {
        config.addArgs(PradarService.PRADAR_WHITE_LIST_CHECK, headers[0].getValue());
    }
    config.addArgs("url", url);
    config.addArgs("request", request);
    config.addArgs("method", "uri");
    config.addArgs("isInterface", Boolean.FALSE);
    config.getStrategy().processBlock(advice.getBehavior().getReturnType(), advice.getClassLoader(), config, new ExecutionCall() {

        @Override
        public Object call(Object param) {
            try {
                HttpEntity entity = null;
                if (param instanceof String) {
                    entity = new StringEntity(String.valueOf(param), Charset.forName("UTF-8"));
                } else {
                    entity = new ByteArrayEntity(JSONObject.toJSONBytes(param), ContentType.create(request.getEntity().getContentType()));
                }
                BasicClassicHttpResponse response = new BasicClassicHttpResponse(200);
                response.setEntity(entity);
                if (HttpClientConstants.clazz == null) {
                    HttpClientConstants.clazz = Class.forName("org.apache.hc.client5.http.impl.classic.CloseableHttpResponse");
                }
                return Reflect.on(HttpClientConstants.clazz).create(response, null).get();
            } catch (Exception e) {
            }
            return null;
        }
    });
}
Also used : ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) HttpEntity(org.apache.hc.core5.http.HttpEntity) MatchConfig(com.pamirs.pradar.internal.config.MatchConfig) URISyntaxException(java.net.URISyntaxException) SocketTimeoutException(java.net.SocketTimeoutException) ProcessControlException(com.shulie.instrument.simulator.api.ProcessControlException) IOException(java.io.IOException) StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) Header(org.apache.hc.core5.http.Header) ByteArrayEntity(org.apache.hc.core5.http.io.entity.ByteArrayEntity) HttpHost(org.apache.hc.core5.http.HttpHost) JSONObject(com.alibaba.fastjson.JSONObject) ExecutionCall(com.pamirs.pradar.internal.config.ExecutionCall) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse)

Example 29 with BasicClassicHttpResponse

use of org.apache.hc.core5.http.message.BasicClassicHttpResponse in project httpcomponents-core by apache.

the class ClassicIntegrationTest method testHttpPostsWithExpectationVerification.

/**
 * This test case executes a series of simple POST requests that do not
 * meet the target server expectations.
 */
@Test
public void testHttpPostsWithExpectationVerification() throws Exception {
    final int reqNo = 20;
    // Initialize the server-side request handler
    this.server.registerHandler("*", (request, response, context) -> response.setEntity(new StringEntity("No content")));
    this.server.start(null, null, handler -> new BasicHttpServerExpectationDecorator(handler) {

        @Override
        protected ClassicHttpResponse verify(final ClassicHttpRequest request, final HttpContext context) {
            final Header someheader = request.getFirstHeader("Secret");
            if (someheader != null) {
                final int secretNumber;
                try {
                    secretNumber = Integer.parseInt(someheader.getValue());
                } catch (final NumberFormatException ex) {
                    final ClassicHttpResponse response = new BasicClassicHttpResponse(HttpStatus.SC_BAD_REQUEST);
                    response.setEntity(new StringEntity(ex.toString()));
                    return response;
                }
                if (secretNumber >= 2) {
                    final ClassicHttpResponse response = new BasicClassicHttpResponse(HttpStatus.SC_EXPECTATION_FAILED);
                    response.setEntity(new StringEntity("Wrong secret number", ContentType.TEXT_PLAIN));
                    return response;
                }
            }
            return null;
        }
    });
    this.client.start();
    final HttpCoreContext context = HttpCoreContext.create();
    final HttpHost host = new HttpHost(scheme.id, "localhost", this.server.getPort());
    for (int r = 0; r < reqNo; r++) {
        final BasicClassicHttpRequest post = new BasicClassicHttpRequest(Method.POST, "/");
        post.addHeader("Secret", Integer.toString(r));
        final byte[] b = new byte[2048];
        for (int i = 0; i < b.length; i++) {
            b[i] = (byte) ('a' + r);
        }
        post.setEntity(new ByteArrayEntity(b, ContentType.TEXT_PLAIN));
        try (final ClassicHttpResponse response = this.client.execute(host, post, context)) {
            final HttpEntity responseEntity = response.getEntity();
            Assertions.assertNotNull(responseEntity);
            EntityUtils.consume(responseEntity);
            if (r >= 2) {
                Assertions.assertEquals(HttpStatus.SC_EXPECTATION_FAILED, response.getCode());
            } else {
                Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
            }
        }
    }
}
Also used : ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) BasicHttpServerExpectationDecorator(org.apache.hc.core5.http.io.support.BasicHttpServerExpectationDecorator) HttpEntity(org.apache.hc.core5.http.HttpEntity) AbstractHttpEntity(org.apache.hc.core5.http.io.entity.AbstractHttpEntity) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) Header(org.apache.hc.core5.http.Header) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ByteArrayEntity(org.apache.hc.core5.http.io.entity.ByteArrayEntity) HttpHost(org.apache.hc.core5.http.HttpHost) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) Test(org.junit.Test)

Example 30 with BasicClassicHttpResponse

use of org.apache.hc.core5.http.message.BasicClassicHttpResponse in project httpcomponents-core by apache.

the class HttpServerExpectationFilter method handle.

@Override
public final void handle(final ClassicHttpRequest request, final HttpFilterChain.ResponseTrigger responseTrigger, final HttpContext context, final HttpFilterChain chain) throws HttpException, IOException {
    final Header expect = request.getFirstHeader(HttpHeaders.EXPECT);
    final boolean expectContinue = expect != null && HeaderElements.CONTINUE.equalsIgnoreCase(expect.getValue());
    if (expectContinue) {
        final boolean verified = verify(request, context);
        if (verified) {
            responseTrigger.sendInformation(new BasicClassicHttpResponse(HttpStatus.SC_CONTINUE));
        } else {
            final ClassicHttpResponse expectationFailed = new BasicClassicHttpResponse(HttpStatus.SC_EXPECTATION_FAILED);
            final HttpEntity responseContent = generateResponseContent(expectationFailed);
            expectationFailed.setEntity(responseContent);
            responseTrigger.submitResponse(expectationFailed);
            return;
        }
    }
    chain.proceed(request, responseTrigger, context);
}
Also used : BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) Header(org.apache.hc.core5.http.Header) HttpEntity(org.apache.hc.core5.http.HttpEntity) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse)

Aggregations

BasicClassicHttpResponse (org.apache.hc.core5.http.message.BasicClassicHttpResponse)69 Test (org.junit.jupiter.api.Test)57 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)56 Header (org.apache.hc.core5.http.Header)34 BasicHeader (org.apache.hc.core5.http.message.BasicHeader)29 BasicClassicHttpRequest (org.apache.hc.core5.http.message.BasicClassicHttpRequest)19 ClassicHttpRequest (org.apache.hc.core5.http.ClassicHttpRequest)14 StringEntity (org.apache.hc.core5.http.io.entity.StringEntity)13 HttpEntity (org.apache.hc.core5.http.HttpEntity)12 HttpCoreContext (org.apache.hc.core5.http.protocol.HttpCoreContext)11 HttpClientConnection (org.apache.hc.core5.http.io.HttpClientConnection)10 HttpProcessor (org.apache.hc.core5.http.protocol.HttpProcessor)10 BasicHttpEntity (org.apache.hc.core5.http.io.entity.BasicHttpEntity)9 TimeValue (org.apache.hc.core5.util.TimeValue)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 IOException (java.io.IOException)6 HttpResponse (org.apache.hc.core5.http.HttpResponse)4 Timeout (org.apache.hc.core5.util.Timeout)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 InputStream (java.io.InputStream)3