http接口返回文件 服务端和客户端

服务端:

    @RequestMapping(value = "/lsj", method = {RequestMethod.POST, RequestMethod.GET}, produces = {"text/plain;charset=UTF-8"})
    @ResponseBody
    public String searchLsjDzzz(String jsonStr,HttpServletResponse httpServletResponse) {
        byte[] dzzz = null;
        //下载PDF
        httpServletResponse.setHeader("Content-Disposition", "attachment;Filename=" + UUID.randomUUID()+".pdf");
        OutputStream outputStream = httpServletResponse.getOutputStream();
        outputStream.write(dzzz);
        outputStream.close();

        return "";
    }

客户端:

    public byte[] requestByGetToByte(String url,String charset){
        if (url == null || "".equals(url))
        {
            log.error("request url is empty.");
            return null;
        }
        HttpClient httpClient = CustomHttpClient.GetHttpClient();
        HttpGet get = new HttpGet(url);
        get.setHeader("Content-Type", "text/html;charset="+charset);
        HttpResponse resp = null;
        try
        {
            // 发起交易
            resp = httpClient.execute(get);
            // 响应分析
            HttpEntity entity = resp.getEntity();
            byte[] bytes= EntityUtils.toByteArray(entity);

            return bytes;
        } catch (ConnectTimeoutException cte){
            log.error(cte.getMessage(), cte);
            return null;
        } catch (SocketTimeoutException cte){
            log.error(cte.getMessage(), cte);
            return null;
        } catch (Exception e){
            log.error(e.getMessage(), e);
            return null;
        }finally{
            try {
                if(resp!=null){
                    resp.getEntity().getContent().close();
                }
            } catch (IllegalStateException e) {
                log.error(e.getMessage(), e);
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

 

posted on 2017-09-23 11:18  13rj1115  阅读(4539)  评论(0编辑  收藏  举报

导航