httpclient 訪問圖片

圖片傳輸采用字節(jié)流
訪問接口:

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

}

具體實(shí)現(xiàn):

public byte[] doGet(String url) throws Exception {
        // 聲明 http get 請求
        HttpGet httpGet = new HttpGet(url);

        // 裝載配置信息
        httpGet.setConfig(config);

        // 發(fā)起請求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        // 判斷狀態(tài)碼是否為200
        if (response.getStatusLine().getStatusCode() == 200) {
            // 返回響應(yīng)體的內(nèi)容
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            response.getEntity().writeTo(baos);
            return baos.toByteArray();
//            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        return null;
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容