post请求返回数据中包含文件

最近在工作中遇到一个需求,post请求查询某个业务记录,返回的数据中除包含该记录的基本信息外,还包含一个PDF文件。调用post请求后,需要将返回结果保存到数据库中,同时将PDF文件存到本地硬盘。经过一番尝试,解决了此需求,现将代码分享出来:

客户端代码:

public static void main(String[] args) {
        httpPost();
    }

    public static void httpPost() {
        JSONObject paramJson = new JSONObject();
        int timeout = 60000; // 超时时间60s
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(timeout)
                .setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();

        HttpPost httpPost = null;
        List<NameValuePair> nvps = null;
        CloseableHttpResponse response = null;
        HttpEntity resEntity = null;
        try {
            httpPost = new HttpPost("http://localhost:8090/invoice/queryInvoice");
            httpPost.setConfig(defaultRequestConfig);
            paramJson.put("busNo", "123456");
            httpPost.setEntity(new StringEntity(JSON.toJSONString(paramJson), Consts.UTF_8));

            response = httpClient.execute(httpPost);
            resEntity = response.getEntity();
            String resStr = EntityUtils.toString(resEntity, Consts.UTF_8);
            EntityUtils.consume(resEntity);
            JSONObject result = JSONObject.parseObject(resStr);
            byte[] pdfFile = result.getBytes("pdfFile");
            saveFile(pdfFile, "D:\\pdfFiles", "123456.pdf");
        } catch (UnsupportedEncodingException e) {
            throw new BizException(e);
        } catch (ClientProtocolException e) {
            throw new BizException(e);
        } catch (SocketTimeoutException e) {
            throw new BizException("调用服务超时", e);
        } catch (ConnectTimeoutException e) {
            throw new BizException("调用服务超时", e);
        } catch (IOException e) {
            throw new BizException(e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @Author administrator
     * @Description 保存byte数组包含的文件到指定路径
     * @Date 22:06 2019/12/22
     * @Param [bfile, filePath, fileName]
     * @return void
     **/
    public static void saveFile(byte[] bfile, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            boolean isDir = dir.isDirectory();
            if (!isDir) {// 目录不存在则先建目录
                try {
                    dir.mkdirs();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

服务端代码:

/**
     * @Author administrator
     * @Description post请求返回结果包含文件
     * @Date 22:02 2019/12/22
     * @Param [request]
     * @return com.alibaba.fastjson.JSONObject
     **/
    @RequestMapping(method = RequestMethod.POST, path = "/queryInvoice")
    @ResponseBody
    public JSONObject queryInvoice(HttpServletRequest request) throws Exception {
        String paraStr = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
        JSONObject paraJson = JSONObject.parseObject(paraStr);
        String busNo = paraJson.getString("busNo");
        byte[] pdfFile = toByteArray("F:\\fapiao\\" + busNo + ".pdf");//读取本地一个PDF文件
        JSONObject result = new JSONObject();
        result.put("busNo", "123456");
        result.put("time", "2019-10-14");
        result.put("pdfFile", pdfFile);
        return result;
    }

    /**
     * @Author administrator
     * @Description 读取本地文件到byte数组
     * @Date 22:01 2019/12/22
     * @Param [filename]
     * @return byte[]
     **/
    public static byte[] toByteArray(String filename) throws IOException {

        File f = new File(filename);
        if (!f.exists()) {
            throw new FileNotFoundException(filename);
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(f));
            int buf_size = 1024;
            byte[] buffer = new byte[buf_size];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, buf_size))) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            bos.close();
        }
    }

 经过测试,发现能够达到预期效果。补充,有时候,可能因为文件过大,导致文件不能正常存储打开,这时候可以考虑采用base64在服务端对byte数组进行编码为字符串,客户端接收后将字符串通过base64解码为byte数组再保存,问题解决。

希望该分享能对需要的朋友有所帮助,不对的地方敬请斧正。

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值