Search in sources :

Example 1 with Method

use of org.apache.hc.core5.http.Method in project webdrivermanager by bonigarcia.

the class WdmServer method exchange.

public String exchange(String url, String method, String json, int timeoutSec) throws IOException {
    String responseContent = null;
    try (CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build()) {
        HttpUriRequestBase request = null;
        switch(method) {
            case GET:
                request = new HttpGet(url);
                break;
            case DELETE:
                request = new HttpDelete(url);
                break;
            default:
            case POST:
                request = new HttpPost(url);
                HttpEntity body = new StringEntity(json);
                request.setEntity(body);
                request.setHeader("Content-Type", "application/json");
                break;
        }
        RequestConfig requestConfig = custom().setConnectTimeout(timeoutSec, TimeUnit.SECONDS).build();
        request.setConfig(requestConfig);
        try (CloseableHttpResponse response = closeableHttpClient.execute(request)) {
            responseContent = IOUtils.toString(response.getEntity().getContent(), UTF_8);
        }
    }
    return responseContent;
}
Also used : CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) RequestConfig(org.apache.hc.client5.http.config.RequestConfig) HttpUriRequestBase(org.apache.hc.client5.http.classic.methods.HttpUriRequestBase) HttpDelete(org.apache.hc.client5.http.classic.methods.HttpDelete) HttpEntity(org.apache.hc.core5.http.HttpEntity) HttpGet(org.apache.hc.client5.http.classic.methods.HttpGet) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)

Example 2 with Method

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

the class AsyncHttpClientv5MethodInterceptor method doBefore.

@Override
public void doBefore(final Advice advice) throws ProcessControlException {
    Object[] args = advice.getParameterArray();
    // HttpHost
    HttpHost httpHost = (HttpHost) args[0];
    if (httpHost == null) {
        return;
    }
    BasicRequestProducer requestBasic = (BasicRequestProducer) args[1];
    final SimpleHttpRequest request;
    try {
        Field field = requestBasic.getClass().getDeclaredField("request");
        field.setAccessible(true);
        request = (SimpleHttpRequest) field.get(requestBasic);
    } catch (Exception e) {
        logger.error("获取request参数错误", e);
        return;
    }
    if (request == null) {
        return;
    }
    String host = httpHost.getHostName();
    int port = httpHost.getPort();
    String path = httpHost.getHostName();
    String reqStr = request.toString();
    String method = StringUtils.upperCase(reqStr.substring(0, reqStr.indexOf(" ")));
    // 判断是否在白名单中
    String url = getService(httpHost.getSchemeName(), host, port, path);
    MatchConfig config = ClusterTestUtils.httpClusterTest(url);
    Header[] wHeaders = request.getHeaders(PradarService.PRADAR_WHITE_LIST_CHECK);
    if (wHeaders != null && wHeaders.length > 0) {
        config.addArgs(PradarService.PRADAR_WHITE_LIST_CHECK, wHeaders[0].getValue());
    }
    config.addArgs("url", url);
    config.addArgs("request", request);
    config.addArgs("method", "uri");
    config.addArgs("isInterface", Boolean.FALSE);
    Pradar.startClientInvoke(path, method);
    Pradar.remoteIp(host);
    Pradar.remotePort(port);
    Pradar.middlewareName(HttpClientConstants.HTTP_CLIENT_NAME_5X);
    Header[] headers = request.getHeaders("content-length");
    if (headers != null && headers.length != 0) {
        try {
            Header header = headers[0];
            Pradar.requestSize(Integer.valueOf(header.getValue()));
        } catch (NumberFormatException e) {
        }
    }
    final Map<String, String> context = Pradar.getInvokeContextMap();
    for (Map.Entry<String, String> entry : context.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        if (request.getHeaders(HeaderMark.DONT_MODIFY_HEADER) == null || request.getHeaders(HeaderMark.DONT_MODIFY_HEADER).length == 0) {
            request.setHeader(key, value);
        }
    }
    // pradar启动提前为的是捕获白名单异常能trace进去的
    try {
        config.getStrategy().processBlock(advice.getBehavior().getReturnType(), advice.getClassLoader(), config, new ExecutionCall() {

            @Override
            public Object call(Object param) {
                // return future;
                return null;
            }
        });
    } catch (PressureMeasureError e) {
        Pradar.response(e);
        Pradar.endClientInvoke(ResultCode.INVOKE_RESULT_FAILED, HttpClientConstants.PLUGIN_TYPE);
        throw e;
    }
    Pradar.popInvokeContext();
    final Object future = args[args.length - 1];
    if (!(future instanceof FutureCallback) && future != null) {
        return;
    }
    advice.changeParameter(args.length - 1, new FutureCallback() {

        @Override
        public void completed(Object result) {
            Pradar.setInvokeContext(context);
            ((FutureCallback) future).completed(result);
            try {
                if (result instanceof SimpleHttpResponse) {
                    afterTrace(request, (SimpleHttpResponse) result);
                } else {
                    afterTrace(request, null);
                }
            } catch (Throwable e) {
                LOGGER.error("AsyncHttpClient execute future endTrace error.", e);
                Pradar.endClientInvoke("200", HttpClientConstants.PLUGIN_TYPE);
            }
        }

        @Override
        public void failed(Exception ex) {
            Pradar.setInvokeContext(context);
            ((FutureCallback) future).failed(ex);
            try {
                exceptionTrace(request, ex);
            } catch (Throwable e) {
                LOGGER.error("AsyncHttpClient execute future endTrace error.", e);
                Pradar.endClientInvoke("200", HttpClientConstants.PLUGIN_TYPE);
            }
        }

        @Override
        public void cancelled() {
            Pradar.setInvokeContext(context);
            ((FutureCallback) future).cancelled();
            try {
                exceptionTrace(request, null);
            } catch (Throwable e) {
                LOGGER.error("AsyncHttpClient execute future endTrace error.", e);
                Pradar.endClientInvoke("200", HttpClientConstants.PLUGIN_TYPE);
            }
        }
    });
}
Also used : BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) MatchConfig(com.pamirs.pradar.internal.config.MatchConfig) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) SocketTimeoutException(java.net.SocketTimeoutException) ProcessControlException(com.shulie.instrument.simulator.api.ProcessControlException) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) Field(java.lang.reflect.Field) Header(org.apache.hc.core5.http.Header) HttpHost(org.apache.hc.core5.http.HttpHost) PressureMeasureError(com.pamirs.pradar.exception.PressureMeasureError) JSONObject(com.alibaba.fastjson.JSONObject) ExecutionCall(com.pamirs.pradar.internal.config.ExecutionCall) Map(java.util.Map) FutureCallback(org.apache.hc.core5.concurrent.FutureCallback)

Example 3 with Method

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

the class HttpClientv5MethodInterceptor1 method beforeLast.

@Override
public void beforeLast(Advice advice) throws ProcessControlException {
    Object[] args = advice.getParameterArray();
    // ClassicHttpRequest
    final ClassicHttpRequest request = (ClassicHttpRequest) args[0];
    if (request == null) {
        return;
    }
    URI uri = null;
    try {
        uri = request.getUri();
    } catch (URISyntaxException e) {
        logger.error("获取不到url", e);
    }
    String host = uri.getHost();
    int port = uri.getPort();
    String path = uri.getPath();
    // 判断是否在白名单中
    String url = getService(uri.getScheme(), host, port, path);
    MatchConfig config = ClusterTestUtils.httpClusterTest(url);
    Header[] headers = request.getHeaders(PradarService.PRADAR_WHITE_LIST_CHECK);
    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));
                } 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 : MatchConfig(com.pamirs.pradar.internal.config.MatchConfig) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) 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) ByteArrayEntity(org.apache.hc.core5.http.io.entity.ByteArrayEntity) JSONObject(com.alibaba.fastjson.JSONObject) ExecutionCall(com.pamirs.pradar.internal.config.ExecutionCall) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse)

Example 4 with Method

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

the class TestHPackCoding method testRequestDecodingWithHuffmanRFC7541Examples.

@Test
public void testRequestDecodingWithHuffmanRFC7541Examples() throws Exception {
    final ByteBuffer src1 = createByteBuffer(0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff);
    final InboundDynamicTable dynamicTable = new InboundDynamicTable();
    final HPackDecoder decoder = new HPackDecoder(dynamicTable, StandardCharsets.US_ASCII);
    final List<Header> headers1 = decoder.decodeHeaders(src1);
    Assertions.assertEquals(4, headers1.size());
    assertHeaderEquals(new BasicHeader(":method", "GET"), headers1.get(0));
    assertHeaderEquals(new BasicHeader(":scheme", "http"), headers1.get(1));
    assertHeaderEquals(new BasicHeader(":path", "/"), headers1.get(2));
    assertHeaderEquals(new BasicHeader(":authority", "www.example.com"), headers1.get(3));
    Assertions.assertEquals(1, dynamicTable.dynamicLength());
    assertHeaderEquals(new BasicHeader(":authority", "www.example.com"), dynamicTable.getDynamicEntry(0));
    Assertions.assertEquals(57, dynamicTable.getCurrentSize());
    final ByteBuffer src2 = createByteBuffer(0x82, 0x86, 0x84, 0xbe, 0x58, 0x86, 0xa8, 0xeb, 0x10, 0x64, 0x9c, 0xbf);
    final List<Header> headers2 = decoder.decodeHeaders(src2);
    Assertions.assertEquals(5, headers2.size());
    assertHeaderEquals(new BasicHeader(":method", "GET"), headers2.get(0));
    assertHeaderEquals(new BasicHeader(":scheme", "http"), headers2.get(1));
    assertHeaderEquals(new BasicHeader(":path", "/"), headers2.get(2));
    assertHeaderEquals(new BasicHeader(":authority", "www.example.com"), headers2.get(3));
    assertHeaderEquals(new BasicHeader("cache-control", "no-cache"), headers2.get(4));
    Assertions.assertEquals(2, dynamicTable.dynamicLength());
    assertHeaderEquals(new BasicHeader("cache-control", "no-cache"), dynamicTable.getDynamicEntry(0));
    assertHeaderEquals(new BasicHeader(":authority", "www.example.com"), dynamicTable.getDynamicEntry(1));
    Assertions.assertEquals(110, dynamicTable.getCurrentSize());
    final ByteBuffer src3 = createByteBuffer(0x82, 0x87, 0x85, 0xbf, 0x40, 0x88, 0x25, 0xa8, 0x49, 0xe9, 0x5b, 0xa9, 0x7d, 0x7f, 0x89, 0x25, 0xa8, 0x49, 0xe9, 0x5b, 0xb8, 0xe8, 0xb4, 0xbf);
    final List<Header> headers3 = decoder.decodeHeaders(src3);
    Assertions.assertEquals(5, headers3.size());
    assertHeaderEquals(new BasicHeader(":method", "GET"), headers3.get(0));
    assertHeaderEquals(new BasicHeader(":scheme", "https"), headers3.get(1));
    assertHeaderEquals(new BasicHeader(":path", "/index.html"), headers3.get(2));
    assertHeaderEquals(new BasicHeader(":authority", "www.example.com"), headers3.get(3));
    assertHeaderEquals(new BasicHeader("custom-key", "custom-value"), headers3.get(4));
    Assertions.assertEquals(3, dynamicTable.dynamicLength());
    assertHeaderEquals(new BasicHeader("custom-key", "custom-value"), dynamicTable.getDynamicEntry(0));
    assertHeaderEquals(new BasicHeader("cache-control", "no-cache"), dynamicTable.getDynamicEntry(1));
    assertHeaderEquals(new BasicHeader(":authority", "www.example.com"), dynamicTable.getDynamicEntry(2));
    Assertions.assertEquals(164, dynamicTable.getCurrentSize());
}
Also used : BasicHeader(org.apache.hc.core5.http.message.BasicHeader) Header(org.apache.hc.core5.http.Header) ByteBuffer(java.nio.ByteBuffer) BasicHeader(org.apache.hc.core5.http.message.BasicHeader) Test(org.junit.jupiter.api.Test)

Example 5 with Method

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

the class TestHPackCoding method testRequestEncodingWithHuffmanRFC7541Examples.

@Test
public void testRequestEncodingWithHuffmanRFC7541Examples() throws Exception {
    final OutboundDynamicTable dynamicTable = new OutboundDynamicTable();
    final HPackEncoder encoder = new HPackEncoder(dynamicTable, StandardCharsets.US_ASCII);
    final ByteArrayBuffer buf = new ByteArrayBuffer(256);
    final List<Header> headers1 = Arrays.asList(new BasicHeader(":method", "GET"), new BasicHeader(":scheme", "http"), new BasicHeader(":path", "/"), new BasicHeader(":authority", "www.example.com"));
    encoder.encodeHeaders(buf, headers1, false, true);
    final byte[] expected1 = createByteArray(0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff);
    Assertions.assertArrayEquals(expected1, buf.toByteArray());
    Assertions.assertEquals(1, dynamicTable.dynamicLength());
    assertHeaderEquals(new BasicHeader(":authority", "www.example.com"), dynamicTable.getDynamicEntry(0));
    Assertions.assertEquals(57, dynamicTable.getCurrentSize());
    final List<Header> headers2 = Arrays.asList(new BasicHeader(":method", "GET"), new BasicHeader(":scheme", "http"), new BasicHeader(":path", "/"), new BasicHeader(":authority", "www.example.com"), new BasicHeader("cache-control", "no-cache"));
    buf.clear();
    encoder.encodeHeaders(buf, headers2, false, true);
    final byte[] expected2 = createByteArray(0x82, 0x86, 0x84, 0xbe, 0x58, 0x86, 0xa8, 0xeb, 0x10, 0x64, 0x9c, 0xbf);
    Assertions.assertArrayEquals(expected2, buf.toByteArray());
    Assertions.assertEquals(2, dynamicTable.dynamicLength());
    assertHeaderEquals(new BasicHeader("cache-control", "no-cache"), dynamicTable.getDynamicEntry(0));
    assertHeaderEquals(new BasicHeader(":authority", "www.example.com"), dynamicTable.getDynamicEntry(1));
    Assertions.assertEquals(110, dynamicTable.getCurrentSize());
    final List<Header> headers3 = Arrays.asList(new BasicHeader(":method", "GET"), new BasicHeader(":scheme", "https"), new BasicHeader(":path", "/index.html"), new BasicHeader(":authority", "www.example.com"), new BasicHeader("custom-key", "custom-value"));
    buf.clear();
    encoder.encodeHeaders(buf, headers3, false, true);
    final byte[] expected3 = createByteArray(0x82, 0x87, 0x85, 0xbf, 0x40, 0x88, 0x25, 0xa8, 0x49, 0xe9, 0x5b, 0xa9, 0x7d, 0x7f, 0x89, 0x25, 0xa8, 0x49, 0xe9, 0x5b, 0xb8, 0xe8, 0xb4, 0xbf);
    Assertions.assertArrayEquals(expected3, buf.toByteArray());
    Assertions.assertEquals(3, dynamicTable.dynamicLength());
    assertHeaderEquals(new BasicHeader("custom-key", "custom-value"), dynamicTable.getDynamicEntry(0));
    assertHeaderEquals(new BasicHeader("cache-control", "no-cache"), dynamicTable.getDynamicEntry(1));
    assertHeaderEquals(new BasicHeader(":authority", "www.example.com"), dynamicTable.getDynamicEntry(2));
    Assertions.assertEquals(164, dynamicTable.getCurrentSize());
}
Also used : BasicHeader(org.apache.hc.core5.http.message.BasicHeader) Header(org.apache.hc.core5.http.Header) BasicHeader(org.apache.hc.core5.http.message.BasicHeader) ByteArrayBuffer(org.apache.hc.core5.util.ByteArrayBuffer) Test(org.junit.jupiter.api.Test)

Aggregations

Header (org.apache.hc.core5.http.Header)38 BasicHeader (org.apache.hc.core5.http.message.BasicHeader)29 Test (org.junit.jupiter.api.Test)29 CloseableHttpResponse (org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)16 IOException (java.io.IOException)15 URI (java.net.URI)14 URISyntaxException (java.net.URISyntaxException)14 Map (java.util.Map)14 HttpEntity (org.apache.hc.core5.http.HttpEntity)13 HttpHost (org.apache.hc.core5.http.HttpHost)12 StringEntity (org.apache.hc.core5.http.io.entity.StringEntity)10 ContentType (org.apache.hc.core5.http.ContentType)9 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)9 HttpRequest (org.apache.hc.core5.http.HttpRequest)8 HashMap (java.util.HashMap)7 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)7 ProtocolVersion (org.apache.hc.core5.http.ProtocolVersion)7 SocketTimeoutException (java.net.SocketTimeoutException)6 ArrayList (java.util.ArrayList)6 BasicNameValuePair (org.apache.hc.core5.http.message.BasicNameValuePair)6