我有一个发送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
}
附言无论如何,我有一个使用Apache的
RequestBuilder
的替代解决方案,我只是想知道是否有上述解决方案。 最佳答案
Get
,Post
...的请求类扩展了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;
}
关于java - 传递一个类,实例化它,然后使用正确的方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47371567/