下面列出了怎么用org.apache.http.impl.client.AbstractResponseHandler的API类实例代码及写法,或者点击链接到github查看源代码。
protected <T> ResponseHandler<T> handleResponse(final Class<T> responseDtoClass) {
return new AbstractResponseHandler<T>() {
@Override
public T handleEntity(HttpEntity responseEntity) {
T deserializedResponse = null;
if (!responseDtoClass.isAssignableFrom(Void.class)) {
try {
deserializedResponse = deserializeResponse(responseEntity, responseDtoClass);
EntityUtils.consume(responseEntity);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return deserializedResponse;
}
};
}
public InputStream executeGET(String url, Header... headers) throws IOException{
HttpGet request = new HttpGet(url);
if (headers != null) {
for (Header header : headers) {
request.addHeader(header);
}
}
addDefaultHeaders(request);
HttpResponse response = this.client.execute(request);
ResponseHandler<InputStream> handler = new AbstractResponseHandler<InputStream>(){
@Override
public InputStream handleEntity(final HttpEntity entity) throws IOException {
return entity.getContent();
}
};
return handler.handleResponse(response);
}
public InputStream executePOST(String url, String payload) throws IOException{
HttpPost request = new HttpPost(url);
addDefaultHeaders(request);
request.setEntity(new StringEntity(payload));
HttpResponse response = this.client.execute(request);
ResponseHandler<InputStream> handler = new AbstractResponseHandler<InputStream>(){
@Override
public InputStream handleEntity(final HttpEntity entity) throws IOException {
return entity.getContent();
}
};
return handler.handleResponse(response);
}
public InputStream executeDELETE(String url) throws IOException {
HttpDelete request = new HttpDelete(url);
addDefaultHeaders(request);
HttpResponse response = this.client.execute(request);
ResponseHandler<InputStream> handler = new AbstractResponseHandler<InputStream>(){
@Override
public InputStream handleEntity(final HttpEntity entity) throws IOException {
return entity.getContent();
}
};
return handler.handleResponse(response);
}
/**
* Returns an entity to function result response handler.
*
* @param <R> the function return type, not null
* @param function the function to apply to the response entity, not null
* @return an entity to function result response handler, not null
*/
public static <R> ResponseHandler<R> of(IOFunction<InputStream, R> function) {
Objects.requireNonNull(function);
return new AbstractResponseHandler<R>() {
@Override
public R handleEntity(HttpEntity entity) throws IOException {
try (InputStream inputStream = entity.getContent()) {
return function.apply(inputStream);
}
}
};
}
/**
* Returns an entity to byte array response handler.
*
* @return an entity to byte array response handler, not null
*/
public static ResponseHandler<byte[]> toByteArray() {
return new AbstractResponseHandler<byte[]>() {
@Override
public byte[] handleEntity(HttpEntity entity) throws IOException {
return EntityUtils.toByteArray(entity);
}
};
}