java转发二进制图片流【原】

 

WxQrCoodTool 

java请求目标系统返回二进制图片的接口,并返回给请求方二进行图片流

前端-->java后台(相当于中转)-->图片服务器后端

    /**
     * 获取小程序二维码,如果调用成功,会直接返回图片二进制内容,如果请求失败,会返回 JSON 格式的数据,根据此解释,应该直接由前端生成,不用绕后台
     * @return
     */
    @RequestMapping(value = {"/getWxACodeUnlimit"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @Override
    public void getWxACodeUnlimit(HttpServletRequest request,HttpServletResponse response, @RequestBody String requestBody ,@RequestParam String accessToken) {
       
        String address = String.join("", configProperty.getUnlimitMiniAppCode(), accessToken);
        try {
            logger.info("获取小程序二维码接口-请求报文:{}",requestBody);
            byte[] resultArray = WxQrCoodTool.sendRequestData(address, requestBody, "utf-8","utf-8",5000, 5000);
            WxQrCoodTool.returnImage(resultArray,response);//返回二进制图片流
           
        } catch (Exception e) {
           
        }
    }

 

 

package com.rosellete.iescp.cshop.tool.http;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

/**
 * http post发送工具,用于接收二进行文件流
 * 该工具类一次性使用,不建议复用,专门针对微信post请求返回图片二进制流的功能进行了定制化处理,如果异常微信还可能会返回json串
 * @author King
 */
public class WxQrCoodTool {
    private static final String DEFAULT_CHARSET = "utf-8";

    public static void main(String[] args) throws Exception {
        String requestUrl = "http://i.ce.cn/ce/img4/jrwx.jpg";
        byte[] resultsArray = WxQrCoodTool.sendRequestData(requestUrl,"requestData",  "GBK", "GBK", 3000, 3000);//大家最终只要使用这一句代码就可调用
        WxQrCoodTool.writeImageToFile(resultsArray,"C:\\Users\\King\\Desktop\\iescp-cshopadmin-activity-boot\\aaaaaa123456789.png");
    }

    /**
     * 发送报文
     *
     * @param appName           应用系统英文名
     * @param requestData       请求报文
     * @param urlStr            请求地址
     * @param connectionTimeout 链接超时时间  1000代表 1秒
     * @param readTimeout       读取超时时间 1000代表1秒
     * @return
     * @throws IOException
     * @author King
     */
    public static byte[] sendRequestData(String urlStr, String requestData, String sendEncoding, String recvEncoding, int connectionTimeout, int readTimeout) throws IOException {
        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        byte[] buff = new byte[1024];
        int len = 0;

        URL url = null;
        HttpURLConnection conn = null;
        ByteArrayOutputStream byteOut = null;
        BufferedReader readInfo = null;
        StringBuffer strBuilder = new StringBuffer();
        OutputStream outputStream = null;
        try {
            System.out.println("请求时间:【" + new Date() + "】");
            System.out.println("请求地址:【" + urlStr + "】");
            System.out.println("请求报文:【" + requestData + "】");
            url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            //conn.setRequestProperty("SOAPAction", "\"\"");
            //conn.setRequestProperty("Accept", "application/soap+xml, application/dime, multipart/related, text/*");
            //如果没有下面这一行代码,服务器端可以通过request.getParameter()和request.getInputStream()都接收到相同信息
            //conn.setRequestProperty("content-type", "text/xml;charset=GBK");
            //如果    有上面这一行代码,服务器端仅能通过request.getInputStream()接收信息
            //conn.setRequestProperty("User-Agent", "Axis/1.4");
            conn.setRequestProperty("Cache-Control", "no-cache");
            conn.setUseCaches(false); //忽略缓存
            conn.setDoOutput(true); //使用 URL 连接进行输出
            conn.setDoInput(true); //使用 URL 连接进行输入
            conn.setConnectTimeout(connectionTimeout);//链接超时
            conn.setReadTimeout(readTimeout);//读取超时
            conn.connect();//建立链接
            byteOut = new ByteArrayOutputStream();
            byteOut.write(requestData.getBytes(sendEncoding));//以指定编码发送,如果有乱码,修改之
            byte[] buf = byteOut.toByteArray();
            outputStream = conn.getOutputStream();
            outputStream.write(buf);
            outputStream.flush();
            inputStream = conn.getInputStream();
            byteArrayOutputStream = new ByteArrayOutputStream();
            while ((len = inputStream.read(buff)) != -1) {
                byteArrayOutputStream.write(buff, 0, len);
            }
            return byteArrayOutputStream.toByteArray();
            //if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {//正确返回
            //    readInfo = new BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),recvEncoding));//以指定编码读取返回信息,如果有乱码,修改之
            //    String line = null;
            //    while ((line = readInfo.readLine()) != null) {
            //        strBuilder.append(line);
            //    }
            //} else {//没有正确返回
            //    readInfo = new BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),recvEncoding));//以指定编码读取返回信息,如果有乱码,修改之
            //    System.out.println("出现异常,返回报文:【"+readInfo+"】");
            //    throw new IOException("url请求出现问题,返回编码:" + conn.getResponseCode());
            //}
            //System.out.println("返回时间:【"+new Date()+"】");
            //System.out.println("返回报文:【"+strBuilder.toString()+"】");
        } catch (UnsupportedEncodingException e) {
            throw e;
        } catch (MalformedURLException e) {
            throw e;
        } catch (IOException e) {
            throw e;
        } finally {
            try {
                if (readInfo != null) {
                    readInfo.close();
                }
                if (byteOut != null) {
                    byteOut.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                if (byteArrayOutputStream != null) {
                    byteArrayOutputStream.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }

            } catch (Exception e) {
                System.out.println("关闭链接出错!" + e.getMessage());
            }

        }
        //return strBuilder.toString();
    }


    /**
     * @param filePath 文件绝对路径
     * @param encoding 读取文件的编码
     * @return
     * @throws Exception
     * @author King
     */
    public static String readStringFromFile(String filePath, String encoding) {
        File file = new File(filePath);
        System.out.println("文件 " + filePath + "存在与否?: " + file.exists() + "\n");
        String tempLine = null;
        String retStr = "";
        InputStreamReader isr = null;//way1:
//        FileReader fr = null;//way2
        StringBuilder sb = new StringBuilder();
        try {
            if (file.exists()) {
                isr = new InputStreamReader(new FileInputStream(file), encoding);//way1:
//                fr = new FileReader(file);//way2
                BufferedReader br = new BufferedReader(isr);//way1:
//                BufferedReader br =  new BufferedReader(fr);;//way2:
                tempLine = br.readLine();
                while (tempLine != null) {
                    sb.append(tempLine);
                    tempLine = br.readLine();
                }
                retStr = sb.toString();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (isr != null)
                    isr.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("读到的文件内容如下:");
        System.out.println(retStr + "\n");
        return retStr;
    }

    /**
     * 通过response返回图片
     *
     * @param response
     * @param resultArray
     */
    public static void returnImage(byte[] resultArray, HttpServletResponse response) {
        response.setContentType("image/png");
        ByteArrayInputStream bais = new ByteArrayInputStream(resultArray);
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();

            //创建存放文件内容的数组
            byte[] buff = new byte[1024];
            //所读取的内容使用n来接收
            int n;
            //当没有读取完时,继续读取,循环
            while ((n = bais.read(buff)) != -1) {
                //将字节数组的数据全部写入到输出流中
                outputStream.write(buff, 0, n);
            }
            //强制将缓存区的数据进行输出
            outputStream.flush();
            //关流
            outputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bais.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 通过response返回图片
     */
    public static void writeImageToFile(byte[] resultArray, String path) {
        ByteArrayInputStream bais = new ByteArrayInputStream(resultArray);
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(path);
            //创建存放文件内容的数组
            byte[] buff = new byte[1024];
            //所读取的内容使用n来接收
            int n;
            //当没有读取完时,继续读取,循环
            while ((n = bais.read(buff)) != -1) {
                //将字节数组的数据全部写入到输出流中
                outputStream.write(buff, 0, n);
            }
            //强制将缓存区的数据进行输出
            outputStream.flush();
            //关流
            outputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

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

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

        }
    }
}

 

posted @ 2020-04-22 09:01  苦涩泪滴  阅读(2067)  评论(0编辑  收藏  举报