All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.aliyun.httpcomponent.httpclient.implementation.ApacheAsyncHttpResponse Maven / Gradle / Ivy

The newest version!
package com.aliyun.httpcomponent.httpclient.implementation;

import com.aliyun.core.http.HttpHeaders;
import com.aliyun.core.http.HttpRequest;
import com.aliyun.core.utils.BaseUtils;
import com.aliyun.apache.hc.client5.http.async.methods.SimpleBody;
import com.aliyun.apache.hc.client5.http.async.methods.SimpleHttpResponse;
import com.aliyun.apache.hc.core5.http.Header;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public final class ApacheAsyncHttpResponse extends ApacheHttpResponseBase {
    private SimpleHttpResponse apacheResponse;

    public ApacheAsyncHttpResponse(HttpRequest httpRequest, SimpleHttpResponse apacheResponse) {
        super(httpRequest, apacheResponse.getCode(), toHeaders(apacheResponse));
        this.apacheResponse = apacheResponse;
    }

    @Override
    public ByteBuffer getBody() {
        byte[] bytes = getBodyAsByteArray();
        return bytes != null ? ByteBuffer.wrap(bytes) : null;
    }

    @Override
    public byte[] getBodyAsByteArray() {
        SimpleBody body = apacheResponse.getBody();
        return body != null ? body.getBodyBytes() : null;
    }

    @Override
    public String getBodyAsString() {
        byte[] bytes = getBodyAsByteArray();
        return bytes != null ? BaseUtils.bomAwareToString(getBodyAsByteArray(), getHeaderValue("Content-Type")) : null;
    }

    @Override
    public String getBodyAsString(Charset charset) {
        byte[] bytes = getBodyAsByteArray();
        return bytes != null ? new String(getBodyAsByteArray(), charset) : null;
    }

    private static HttpHeaders toHeaders(SimpleHttpResponse response) {
        final HttpHeaders httpHeaders = new HttpHeaders();
        Set nameSet = new HashSet<>();
        Header[] apacheHeaders = response.getHeaders();
        for (Header header : apacheHeaders) {
            nameSet.add(header.getName());
        }
        nameSet.forEach((name) -> {
            Header[] entityHeaders = response.getHeaders(name);
            List values = new ArrayList<>();
            for (Header entityHeader : entityHeaders) {
                values.add(entityHeader.getValue());
            }
            httpHeaders.set(name, values);
        });
        return httpHeaders;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy