帮助中心 > 通信 > API文档 > 代码示例 > Java

Java

代码示例需要依赖如下jar包

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20190722</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.4</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.4</version>
</dependency>

示例代码:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.util.*;

public class SmsDemo {
    private final static String accessId        = "*****";
    private final static String accessSecret    = "*****";

    public static String sign(String s, String key, String method) throws Exception {
        Mac mac = Mac.getInstance(method);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), mac.getAlgorithm());
        mac.init(secretKeySpec);
        byte[] hash = mac.doFinal(s.getBytes("UTF-8"));
        return DatatypeConverter.printBase64Binary(hash);
    }

    public static String getStringToSign(TreeMap<String, Object> params) {
        StringBuilder s2s = new StringBuilder();
        // 签名时要求对参数进行字典排序,此处用TreeMap保证顺序
        for (String k : params.keySet()) {
            s2s.append(k).append("=").append(params.get(k).toString()).append("&");
        }
        return s2s.toString().substring(0, s2s.length() - 1);
    }

    public static void main(String[] args) throws Exception {
        String url = "https://api.yisu.com/sms/sendSms";
        TreeMap<String, Object> params = new TreeMap<String, Object>(); // TreeMap可以自动排序
        Map<String, Object> vars = new HashMap<String, Object>(); // 模板变量
        vars.put("code", 123123);
        vars.put("min", 5);
        JSONObject varsJson = new JSONObject(vars);
        params.put("templateVars", varsJson.toString());
        params.put("nonce", new Random().nextInt(java.lang.Integer.MAX_VALUE)); // 生成随机数
        params.put("timestamp", System.currentTimeMillis() / 1000); // 时间戳
        params.put("templateCode", "100001"); // 模板号码
        params.put("accessId", accessId);
        params.put("phone", "13800000000");  // 手机号码
        params.put("signature", sign(getStringToSign(params), accessSecret, "HmacSHA1")); // 签名

        // 将所有参数和签名添加到post请求参数数组里
        List<NameValuePair> postparams = new ArrayList<NameValuePair>();
        for (String s : params.keySet()) {
            postparams.add(new BasicNameValuePair(s, params.get(s).toString()));
        }

        HttpPost httpPost = new HttpPost(url);
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(postparams, "utf8"));
            CloseableHttpClient httpClient;
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000).setSocketTimeout(100000).build();
            httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            System.out.println(EntityUtils.toString(entity));

        } catch (Exception e) {
            System.out.println(e.toString());
        } finally {
            httpPost.releaseConnection();
        }
    }
}
免费拨打  400 100 2938 免费拨打 400 100 2938
24小时售后技术支持 24小时售后技术支持
返回顶部 返回顶部