package com.ruoyi.common.utils.sms;

import com.ruoyi.common.utils.sign.Md5Utils;
import okhttp3.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SmsSenderUtils {

    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    private static final OkHttpClient client = new OkHttpClient();

    public static void sendSms(String phoneNumber, String contents) throws IOException {
        // 替换为你的短信服务提供商的API URL
        String url = "http://demo.dgtis.com/smscat/sms/sendSms";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(new Date());
        String md5 = "phones=" + phoneNumber + "&key=dgtissms&date=" + date;
        md5 = Md5Utils.hash(md5);

        RequestBody formBody = new FormBody.Builder()
                .add("phones",phoneNumber)
                .add("contents",contents)
                .add("md5",md5)
                .build();

        // 创建请求
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();

        // 发送请求并获取响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            } else {
                // 处理响应，例如打印响应体
                System.out.println(response.body().string());
            }
        }
    }

    public static void main(String[] args) {
        SmsSenderUtils sender = new SmsSenderUtils();
        try {
            sender.sendSms("15896567520", "Hello, this is a test message!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
