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

Posted 13rj1115

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
            }
        }
    }

 

以上是关于http接口返回文件 服务端和客户端的主要内容,如果未能解决你的问题,请参考以下文章

Chrome接口调试工具

postman做接口自动化测试

golang实现get和post请求的服务端和客户端

HTTP API响应数据规范整理

Http 学习笔记

node web模块 (服务器端和客户端)