package com.muyu.util;


import io.micrometer.common.util.StringUtils;
import okhttp3.*;

import java.io.IOException;

public class WechatUtil {

    public static void send(String toUser,String content) {
        String accessToken = TokenUtil.getAccessToken();
        if (!StringUtils.isBlank(accessToken)) {
            String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken;
            String jsonStr = "{\"touser\":\"" + toUser + "\",\"msgtype\":\"text\",\"text\":{\"content\":\"" + content + "\"}}";
            OkHttpClient client = new OkHttpClient();

            // 构建请求
            RequestBody requestBody = RequestBody.create(jsonStr, MediaType.get("application/json; charset=utf-8"));
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .addHeader("Content-Type", "application/json; charset=utf-8")
                    .build();

            // 发送请求
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }
                // 输出响应
                System.out.println(response.body().string());
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
