我有一个发送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
}
有效。
但我不想为Head
,Put
,Options
等创建另外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
的替代解决方案,如果有上述解决方案,我只是感兴趣。
答案 0 :(得分:1)
document.getElementById("div").style.height = height;
的请求类,Get
...延长Post
,因此您可以相应地限制HttpRequestBase
:
T
答案 1 :(得分:1)
对于确切描述的情况,您可能希望使用工厂函数(Function<String, HttpRequestBase> requestFactory
)和方法参考(HttpGet::new
,HttpPost::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());
}
}
}