【java】下載文件字節數組

    public static byte[] loadFromUrl(String url) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader(RemoteFileUtil.REQUEST_HEADER_X_REQ, RemoteFileUtil.REQUEST_HEADER_X_REQ_NAME);
            httpGet.setHeader(RemoteFileUtil.REQUEST_HEADER_X_TRACE, ContextHolderEx.getSourceId());
            HttpResponse httpResponse = httpClient.execute(httpGet);
            boolean isJson = httpResponse.getEntity().getContentType().getValue().contains("json");
            if (isJson) {
                String message = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
                log.warn("文件下載失敗:{}", message);
                throw new IllegalArgumentException(JSON.parseObject(message).getString("message"));
            }
            return EntityUtils.toByteArray(httpResponse.getEntity());
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章