JAVA 异步通过微信返回的url获取到用户头像并保存到指定目录

  1. 全局创建线程池
 private ExecutorService service = Executors.newFixedThreadPool(20); 
  1. 使用线程池异步执行头像保存任务

    List<Runnable> taskList = new ArrayList<>();
    if(userService.initUserInfo(newInfo) > 0){
        // 用户创建成功后创建线程池将用户信息异步存储到服务器上
        taskList.add(new Runnable() {
            @Override
            public void run() {
                long start = System.currentTimeMillis();
                // 请求
                saveWechatHeadimg(newInfo.getWechatHeadimgurl());
                log.info("getWechatHeadimgurl: {}, time : {} " ,newInfo.getWechatHeadimgurl(),(System.currentTimeMillis() - start));
            }
        });
    }
    service.submit(() -> {
        if(taskList.size() > 0){
            try {
                for(Runnable runnable : taskList){
                    runnable.run();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    });
  1. 保存头像到服务器指定目录
 	/**
     * 保存微信头像
     * @line https://blog.csdn.net/neu_yousei/article/details/22413855
     * @param wechatHeadimgurl 微信头像url
     */
    public void saveWechatHeadimg(String wechatHeadimgurl) {
        if (wechatHeadimgurl != null) {
            InputStream inputStream = null;
            HttpURLConnection httpURLConnection = null;
            FileOutputStream fileOutputStream = null;
            try {
                URL url = new URL(wechatHeadimgurl);
                httpURLConnection = (HttpURLConnection) url.openConnection();
                // 设置网络连接超时时间
                httpURLConnection.setConnectTimeout(10000);
                // 设置应用程序要从网络连接读取数据
                httpURLConnection.setDoInput(true);
                httpURLConnection.setRequestMethod("GET");
                int responseCode = httpURLConnection.getResponseCode();
                if (responseCode == 200) {
                    // 从服务器返回一个输入流
                    inputStream = httpURLConnection.getInputStream();
                }
                if (inputStream != null) {
                    // 创建文件夹
                    String filePath = wechatConfig.getWechatHeadImgUrl() + url.getPath() + "/";
                    String[] paths = filePath.split("/");
                    String fileName = paths[paths.length - 1] + ".jpg";

                    byte[] data = new byte[1024];
                    int len;
                    StringBuilder fullPath = new StringBuilder();
                    for (int i = 0; i < paths.length; i++) {
                        fullPath.append(paths[i]).append("/");
                        File file = new File(fullPath.toString());
                        if (!file.exists()) {
                            file.mkdir();
                        }
                    }
                    // 文件写入
                    fileOutputStream = new FileOutputStream(filePath + fileName);
                    while ((len = inputStream.read(data)) != -1) {
                        fileOutputStream.write(data, 0, len);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }

        }
    }

参考文档:JAVA用http协议GET方法从服务器获取图片保存到本地

你可能感兴趣的:(工作代码片段,java,微信,线程池,流处理)