package com.ruoyi.logistics.util;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.net.URLEncoder;

public class GemaiyunSmsUtil {
    /**
     * 发送歌麦云短信
     */
    public static String sendSms(String apiUrl,
                                 String accesskey,
                                 String secret,
                                 String sign,
                                 String templateId,
                                 String mobile,
                                 String content) throws Exception {

        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(apiUrl);

        postMethod.getParams().setContentCharset("UTF-8");
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler());

        // 封装参数
        NameValuePair[] data = {
                new NameValuePair("accesskey", accesskey),
                new NameValuePair("secret", secret),
                new NameValuePair("sign", sign),
                new NameValuePair("templateId", templateId),
                new NameValuePair("mobile", mobile),
                new NameValuePair("content", URLEncoder.encode(content, "utf-8"))
        };

        postMethod.setRequestBody(data);
        postMethod.setRequestHeader("Connection", "close");

        int statusCode = httpClient.executeMethod(postMethod);
        String result = postMethod.getResponseBodyAsString();

        postMethod.releaseConnection();
        return "statusCode:" + statusCode + ", body:" + result;
    }
}
