Search in sources :

Example 1 with ClassicRequestBuilder

use of org.apache.hc.core5.http.io.support.ClassicRequestBuilder 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)

Aggregations

URI (java.net.URI)1 ByteArrayEntity (org.apache.hc.core5.http.io.entity.ByteArrayEntity)1 StringEntity (org.apache.hc.core5.http.io.entity.StringEntity)1 ClassicRequestBuilder (org.apache.hc.core5.http.io.support.ClassicRequestBuilder)1 URIBuilder (org.apache.hc.core5.net.URIBuilder)1