二维码保存到本地Java代码

工具类

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class WxaQrCodeUtil {
    /**
     * 二维码保存到本地
     * @param bytes
     * @param path 保存到本地的路径
     */
    public static void saveQrCodeToLocal(byte[] bytes, String path) {
        try {
            InputStream inputStream = new ByteArrayInputStream(bytes);
            //文件夹不存在则自动创建
            File tempFile = new File(path);
            if (!tempFile.getParentFile().exists()) {
                tempFile.getParentFile().mkdirs();
            }
            FileOutputStream out = new FileOutputStream(path);
            byte[] buffer = new byte[8192];
            int bytesRead = 0;
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();
            inputStream.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

调用方法

    
        byte[] result = HttpUtil.postHttp(url+token,map);
        String fileName = userId + ".png";
        String path = "D:\\work\" + File.separator + fileName;
        WxaQrCodeUtil.saveQrCodeToLocal(result, path);

post请求

    public static RestTemplate restTemplate;//resttemplate会自动关闭连接
    @Autowired
    public HttpUtil(RestTemplate restTemplate){
        HttpUtil.restTemplate = restTemplate;
    }

    public static byte[] postHttp(String url, Map<String,Object> map) {
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        org.springframework.http.HttpEntity requestEntity = new org.springframework.http.HttpEntity(map, headers);
        ResponseEntity<byte[]> entity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
        return entity.getBody();
    }

 

posted @ 2023-11-17 16:11  白玉神驹  阅读(90)  评论(0)    收藏  举报