httpclient 访问图片

图片传输采用字节流
访问接口:

@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;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容