美文网首页
httpclient 访问图片

httpclient 访问图片

作者: MinaLing | 来源:发表于2019-03-26 17:51 被阅读0次

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

    @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;
        }
    

    相关文章

      网友评论

          本文标题:httpclient 访问图片

          本文链接:https://www.haomeiwen.com/subject/kgenvqtx.html