工具类
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(); }
标签:Java,import,restTemplate,二维码,本地,path,new,byte,public From: https://www.cnblogs.com/cgy-home/p/17839033.html