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

时间:2017-11-18 22:08:23

标签: java generics apache-httpclient-4.x

我有一个发送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种几乎相同的方法。

我可以通过传入一个类来泛化这个方法吗?含义

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的替代解决方案,如果有上述解决方案,我只是感兴趣。

2 个答案:

答案 0 :(得分:1)

document.getElementById("div").style.height = height; 的请求类,Get ...延长Post,因此您可以相应地限制HttpRequestBase

T

答案 1 :(得分:1)

对于确切描述的情况,您可能希望使用工厂函数(Function<String, HttpRequestBase> requestFactory)和方法参考(HttpGet::newHttpPost::new等)来获得所需的结果。< / p>

请使用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());
        }
    }
}