@Override
public byte[] downloadImageByUrl(String imageUrl) {
// TODO Auto-generated method stub
requireAuthorization();
ClientHttpRequestInterceptor acceptHeaderPdf = new AcceptHeaderHttpRequestInterceptor(
"application/jpg");
List<ClientHttpRequestInterceptor> clist = new ArrayList<ClientHttpRequestInterceptor>();
clist.add(acceptHeaderPdf);
restTemplate.setInterceptors(clist);
byte[] response = restTemplate.getForObject(imageUrl, byte[].class);
return response;
}
class AcceptHeaderHttpRequestInterceptor implements
ClientHttpRequestInterceptor {
private final String headerValue;
public AcceptHeaderHttpRequestInterceptor(String headerValue) {
this.headerValue = headerValue;
}
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request);
List<MediaType> mytype = new ArrayList<MediaType>();
mytype.add(MediaType.valueOf(headerValue));
requestWrapper.getHeaders().setAccept(mytype);
return execution.execute(requestWrapper, body);
}
}参考:http://www.ignite.ee/resttemplate-with-custom-http-headers/
本文介绍了一种使用Spring的RestTemplate结合自定义请求头来下载指定URL图片的方法,并通过设置Accept头为application/jpg实现对特定类型图片的支持。
2208

被折叠的 条评论
为什么被折叠?



