图片传输采用字节流
访问接口:
@Slf4j
@Controller
@RequestMapping(value = "/test", produces = "application/json; charset = utf-8")
public class HttpClientTest {
@Autowired
private HttpServiceImp httpServiceImp;
@ResponseBody
@RequestMapping(value = "/http", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] queryEventCount(HttpServletResponse httpResponse) {
try {
return httpServiceImp.doGet("http://***");
} catch (Exception e) {
// TODO Auto-generated catch block
log.warn("error: {}", e);
}
return null;
}
}
具体实现:
public byte[] doGet(String url) throws Exception {
// 声明 http get 请求
HttpGet httpGet = new HttpGet(url);
// 装载配置信息
httpGet.setConfig(config);
// 发起请求
CloseableHttpResponse response = this.httpClient.execute(httpGet);
// 判断状态码是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 返回响应体的内容
ByteArrayOutputStream baos = new ByteArrayOutputStream();
response.getEntity().writeTo(baos);
return baos.toByteArray();
// return EntityUtils.toString(response.getEntity(), "UTF-8");
}
return null;
}