传递一个 class,实例化它并使用正确的方法

Pass a class, instantiate it and and use the right method

我有一个用于发送 Get 请求的包装器方法:

public CloseableHttpResponse sendGetWithHeaders(String url, Map<String, String> headers) {

    HttpGet httpget = new HttpGet(url);

    // loop over entrySet() and httpget.setHeader(key, value);

    return client.execute(httpget); // client instantiated elsewhere
}

有效。

但我不想为 HeadPutOptions 等创建另外 5 个以上几乎相同的方法

我可以通过传入 Class 来生成此方法吗?含义

sendRequestWithHeaders(HttpGet.class, "url", someMap)

以下尝试失败:

CloseableHttpResponse sendRequestWithHeaders(Class<?> clazz, String url, Map<String, String> headers) {

    Object request = clazz.newInstance();
    // request.setHeader(key, value); doesn't compile because it's of type Object
}

<T> CloseableHttpResponse sendRequestWithHeaders(Class<T> clazz, String url, Map<String, String> headers) {

    Object request = clazz.newInstance();
    T t = clazz.cast(request);

    // setHeader(key, value); doesn't compile either because T is generic
}

P.S。无论如何,我有一个使用 Apache RequestBuilder 的替代解决方案,我只是想知道是否有针对上述问题的解决方案。

类 对 GetPost 的请求...扩展 HttpRequestBase,因此您可以相应地限制 T

public <T extends HttpRequestBase> CloseableHttpResponse sendRequestWithHeaders(Class<T> clazz, String url, Map<String, String> headers) throws IOException {
    CloseableHttpResponse response = null;
    try {
        HttpRequestBase request = clazz.getConstructor(String.class).newInstance(url);
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                request.setHeader(header.getKey(), header.getValue());
            }
        }
        response = client.execute(request);
    } catch (Exception ex) {
        // handle exception
    }
    return response;
}

对于所描述的确切情况,您可能需要使用工厂函数 (Function<String, HttpRequestBase> requestFactory) 和方法引用(HttpGet::newHttpPost::new 等)来实现所需的结果.

请考虑以下使用 Apache HttpClient 4.5.3 的实施草案:

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

public class Program {
    public static void main(String[] args) throws IOException {
        try (final CloseableHttpResponse response = CustomHttpClient.sendRequestWithHeaders(
            HttpGet::new,
            "http://apache.org/",
            new HashMap<>())) {
            System.out.println(response.getStatusLine());
            final HttpEntity entity = response.getEntity();
            final String bodyAsString = EntityUtils.toString(entity);
            System.out.println(bodyAsString);
            EntityUtils.consume(entity);
        }
    }

    private static class CustomHttpClient {
        private CustomHttpClient() {
        }

        public static CloseableHttpResponse sendRequestWithHeaders(
            final Function<String, HttpRequestBase> requestFactory,
            final String url,
            final Map<String, String> headers) throws IOException {
            final CloseableHttpClient client = HttpClients
                .custom()
                .setDefaultHeaders(createHeaders(headers))
                .build();
            return client.execute(requestFactory.apply(url));
        }

        private static Collection<Header> createHeaders(final Map<String, String> headers) {
            return headers.entrySet()
                .stream()
                .map(entry -> new BasicHeader(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());
        }
    }
}