Search in sources :

Example 1 with ClassicHttpRequest

use of org.apache.hc.core5.http.ClassicHttpRequest in project feign by OpenFeign.

the class ApacheHttp5Client method toClassicHttpRequest.

ClassicHttpRequest toClassicHttpRequest(Request request, Request.Options options) throws URISyntaxException {
    final ClassicRequestBuilder requestBuilder = ClassicRequestBuilder.create(request.httpMethod().name());
    final URI uri = new URIBuilder(request.url()).build();
    requestBuilder.setUri(uri.getScheme() + "://" + uri.getAuthority() + uri.getRawPath());
    // request query params
    final List<NameValuePair> queryParams = URLEncodedUtils.parse(uri, requestBuilder.getCharset());
    for (final NameValuePair queryParam : queryParams) {
        requestBuilder.addParameter(queryParam);
    }
    // request headers
    boolean hasAcceptHeader = false;
    for (final Map.Entry<String, Collection<String>> headerEntry : request.headers().entrySet()) {
        final String headerName = headerEntry.getKey();
        if (headerName.equalsIgnoreCase(ACCEPT_HEADER_NAME)) {
            hasAcceptHeader = true;
        }
        if (headerName.equalsIgnoreCase(Util.CONTENT_LENGTH)) {
            // doesn't like us to set it as well.
            continue;
        }
        for (final String headerValue : headerEntry.getValue()) {
            requestBuilder.addHeader(headerName, headerValue);
        }
    }
    // some servers choke on the default accept string, so we'll set it to anything
    if (!hasAcceptHeader) {
        requestBuilder.addHeader(ACCEPT_HEADER_NAME, "*/*");
    }
    // request body
    // final Body requestBody = request.requestBody();
    byte[] data = request.body();
    if (data != null) {
        HttpEntity entity;
        if (request.isBinary()) {
            entity = new ByteArrayEntity(data, null);
        } else {
            final ContentType contentType = getContentType(request);
            entity = new StringEntity(new String(data), contentType);
        }
        requestBuilder.setEntity(entity);
    } else {
        requestBuilder.setEntity(new ByteArrayEntity(new byte[0], null));
    }
    return requestBuilder.build();
}
Also used : URI(java.net.URI) URIBuilder(org.apache.hc.core5.net.URIBuilder) StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) ByteArrayEntity(org.apache.hc.core5.http.io.entity.ByteArrayEntity) ClassicRequestBuilder(org.apache.hc.core5.http.io.support.ClassicRequestBuilder)

Example 2 with ClassicHttpRequest

use of org.apache.hc.core5.http.ClassicHttpRequest in project chatty by chatty.

the class Request method apache.

private void apache() {
    if (listener == null) {
        return;
    }
    String responseText = null;
    int responseCode = -1;
    int ratelimitRemaining = -1;
    String responseEncoding = null;
    String requestError = null;
    LOGGER.info(String.format("%s*%s: %s", requestMethod, token != null ? " (auth) " : "", url));
    RequestConfig config = RequestConfig.custom().setConnectTimeout(Timeout.ofMilliseconds(CONNECT_TIMEOUT)).setResponseTimeout(30, TimeUnit.SECONDS).build();
    try (CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(config).build()) {
        ClassicHttpRequest request = new HttpUriRequestBase(requestMethod, new URI(url));
        request.addHeader("Client-ID", CLIENT_ID);
        if (token != null) {
            request.addHeader("Authorization", "Bearer " + token);
        }
        if (data != null) {
            StringEntity stringEntity;
            if (contentType.equals("application/json")) {
                stringEntity = new StringEntity(data, ContentType.APPLICATION_JSON, "UTF-8", false);
            } else {
                stringEntity = new StringEntity(data, CHARSET);
            }
            request.setEntity(stringEntity);
            LOGGER.info("Sending data: " + data);
        }
        try (CloseableHttpResponse response = httpclient.execute(request)) {
            responseCode = response.getCode();
            responseEncoding = getStringHeader(response.getFirstHeader("Content-Encoding"), null);
            ratelimitRemaining = getIntHeader(response.getFirstHeader("Ratelimit-Remaining"), -1);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                responseText = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
                EntityUtils.consume(responseEntity);
            }
        }
    } catch (IOException | URISyntaxException | ParseException ex) {
        requestError = ex.toString();
    }
    // -----------------------
    // Debug output / Output
    // -----------------------
    LOGGER.info(String.format("GOT (%d/%d, %d%s): %s%s", responseCode, ratelimitRemaining, responseText != null ? responseText.length() : -1, responseEncoding != null ? ", " + responseEncoding : "", url, requestError != null ? " [" + requestError + "]" : ""));
    listener.requestResult(responseText, responseCode, ratelimitRemaining);
}
Also used : RequestConfig(org.apache.hc.client5.http.config.RequestConfig) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) HttpUriRequestBase(org.apache.hc.client5.http.classic.methods.HttpUriRequestBase) HttpEntity(org.apache.hc.core5.http.HttpEntity) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) ParseException(org.apache.hc.core5.http.ParseException)

Example 3 with ClassicHttpRequest

use of org.apache.hc.core5.http.ClassicHttpRequest 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 ClassicHttpRequest

use of org.apache.hc.core5.http.ClassicHttpRequest in project logbook by zalando.

the class LocalRequestTest method shouldReturnContentTypesCharsetIfGiven.

@Test
void shouldReturnContentTypesCharsetIfGiven() {
    final ClassicHttpRequest delegate = get("/");
    delegate.addHeader("Content-Type", "text/plain;charset=ISO-8859-1");
    final LocalRequest unit = unit(delegate);
    assertThat(unit.getCharset()).isEqualTo(StandardCharsets.ISO_8859_1);
}
Also used : BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) Test(org.junit.jupiter.api.Test)

Example 5 with ClassicHttpRequest

use of org.apache.hc.core5.http.ClassicHttpRequest in project logbook by zalando.

the class LocalRequestTest method shouldReturnContentTypeHeader.

@Test
void shouldReturnContentTypeHeader() {
    final ClassicHttpRequest delegate = get("/");
    delegate.addHeader("Content-Type", "text/plain;");
    final LocalRequest unit = unit(delegate);
    assertThat(unit.getHeaders()).hasSize(1);
}
Also used : BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) Test(org.junit.jupiter.api.Test)

Aggregations

ClassicHttpRequest (org.apache.hc.core5.http.ClassicHttpRequest)94 Test (org.junit.jupiter.api.Test)69 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)53 BasicClassicHttpRequest (org.apache.hc.core5.http.message.BasicClassicHttpRequest)52 HttpCoreContext (org.apache.hc.core5.http.protocol.HttpCoreContext)32 StringEntity (org.apache.hc.core5.http.io.entity.StringEntity)29 HttpEntity (org.apache.hc.core5.http.HttpEntity)25 BasicClassicHttpResponse (org.apache.hc.core5.http.message.BasicClassicHttpResponse)24 HttpHost (org.apache.hc.core5.http.HttpHost)23 Header (org.apache.hc.core5.http.Header)16 IOException (java.io.IOException)14 HttpClientConnection (org.apache.hc.core5.http.io.HttpClientConnection)13 HttpProcessor (org.apache.hc.core5.http.protocol.HttpProcessor)12 ByteArrayEntity (org.apache.hc.core5.http.io.entity.ByteArrayEntity)11 CloseableHttpClient (org.apache.hc.client5.http.impl.classic.CloseableHttpClient)10 ByteArrayInputStream (java.io.ByteArrayInputStream)9 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 ProtocolVersion (org.apache.hc.core5.http.ProtocolVersion)8 Timeout (org.apache.hc.core5.util.Timeout)8