Httpclient 上传下载文件

 上传文件

 public String mediaUploadFile(String url, String filePath, String type)  {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String accessToken = getAccessToken(false);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("X-Auth0-Token", accessToken);

        // 把文件转换成流对象FileBody
        FileBody bin = new FileBody(new File(filePath));
        StringBody fileType = new StringBody(type, ContentType.create(
                "text/plain", Consts.UTF_8));
        HttpEntity reqEntity = MultipartEntityBuilder.create()
                // 相当于<input type="file" name="file"/>
                .addPart("file", bin)
                .addPart("type", fileType)
                // 相当于<input type="text" name="userName" value=userName>
                .build();

        httpPost.setEntity(reqEntity);


        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
            if (responseContent.isEmpty()) {
                //返回
            }

         
            log.debug("\n【请求地址】: {}\n【Token】:{}\n【响应数据】:{}", url, accessToken, responseContent);
            return responseContent;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }

        throw new RuntimeException("服务端异常");
    }

 下载文件

  public void mediaDownloadFile(String url, String param,HttpServletResponse response)  {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String accessToken = getAccessToken(false);

        HttpGet httpget = new HttpGet(url+"?"+param);
        httpget.setHeader("X-Auth0-Token", accessToken);
        httpget.setHeader("Content-Type", "application/json;charset=UTF-8");

        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            HttpResponse execute = httpClient.execute(httpget);
            outputStream = response.getOutputStream();
            log.debug("\n【请求地址】: {}\n【Token】:{}", url, accessToken);
            // 获取响应对象
            HttpEntity entity = execute.getEntity();
            if (execute.getStatusLine().getStatusCode() != 200) {
                log.error(EntityUtils.toString(execute.getEntity(), Consts.UTF_8));
               return;
            }
            response.setContentType(getContentType(url));
//            response.setHeader("Content-Disposition", "attachment;filename="
//                    .concat(String.valueOf(URLEncoder.encode(UUID.randomUUID().toString().replace("-",""), "UTF-8"))));

            inputStream = entity.getContent();


            //stream 转byte
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            //buff用于存放循环读取的临时数据
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = inputStream.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            byte[] bytes = swapStream.toByteArray();


            Image img = ImageIO.read(new ByteArrayInputStream(bytes));
            // 如果不是图片
            if (img == null) {
                log.error("文件不存在");
               return;
            }else {
                outputStream.write(bytes);
                outputStream.flush();
            }
            // 销毁
            EntityUtils.consume(entity);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(inputStream!=null){
                    inputStream.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(outputStream!=null){
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值