學習時長:4.5小時
程式碼行數:121行
部落格數量:1篇
今日主要學習了呼叫阿里雲api來完成傳送簡訊驗證碼
首先要在阿里雲開通簡訊服務
然後申請資質,建立模板。
然後使用api使用
然後就會生成對應的sdk示例
// This file is auto-generated, don't edit it. Thanks. package demo; import com.aliyun.auth.credentials.Credential; import com.aliyun.auth.credentials.provider.StaticCredentialProvider; import com.aliyun.core.http.HttpClient; import com.aliyun.core.http.HttpMethod; import com.aliyun.core.http.ProxyOptions; import com.aliyun.httpcomponent.httpclient.ApacheAsyncHttpClientBuilder; import com.aliyun.sdk.service.dysmsapi20170525.models.*; import com.aliyun.sdk.service.dysmsapi20170525.*; import com.google.gson.Gson; import darabonba.core.RequestConfiguration; import darabonba.core.client.ClientOverrideConfiguration; import darabonba.core.utils.CommonUtil; import darabonba.core.TeaPair; //import javax.net.ssl.KeyManager; //import javax.net.ssl.X509TrustManager; import java.net.InetSocketAddress; import java.time.Duration; import java.util.*; import java.util.concurrent.CompletableFuture; import java.io.*; public class SendSms { public static void main(String[] args) throws Exception { // HttpClient Configuration /*HttpClient httpClient = new ApacheAsyncHttpClientBuilder() .connectionTimeout(Duration.ofSeconds(10)) // Set the connection timeout time, the default is 10 seconds .responseTimeout(Duration.ofSeconds(10)) // Set the response timeout time, the default is 20 seconds .maxConnections(128) // Set the connection pool size .maxIdleTimeOut(Duration.ofSeconds(50)) // Set the connection pool timeout, the default is 30 seconds // Configure the proxy .proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("<your-proxy-hostname>", 9001)) .setCredentials("<your-proxy-username>", "<your-proxy-password>")) // If it is an https connection, you need to configure the certificate, or ignore the certificate(.ignoreSSL(true)) .x509TrustManagers(new X509TrustManager[]{}) .keyManagers(new KeyManager[]{}) .ignoreSSL(false) .build();*/ // Configure Credentials authentication information, including ak, secret, token StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder() // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set. .accessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")) .accessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")) //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token .build()); // Configure the Client AsyncClient client = AsyncClient.builder() .region("cn-beijing") // Region ID //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient) .credentialsProvider(provider) //.serviceConfiguration(Configuration.create()) // Service-level configuration // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc. .overrideConfiguration( ClientOverrideConfiguration.create() // Endpoint 請參考 https://api.aliyun.com/product/Dysmsapi .setEndpointOverride("dysmsapi.aliyuncs.com") //.setConnectTimeout(Duration.ofSeconds(30)) ) .build(); // Parameter settings for API request SendSmsRequest sendSmsRequest = SendSmsRequest.builder() .signName("")//簽名名稱 .templateCode("")//模板程式碼 .phoneNumbers("")//電話 .templateParam("{\"code\":\"1234\"}") // Request-level configuration rewrite, can set Http request parameters, etc. // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders())) .build(); // Asynchronously get the return value of the API request CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest); // Synchronously get the return value of the API request SendSmsResponse resp = response.get(); System.out.println(new Gson().toJson(resp)); // Asynchronous processing of return values /*response.thenAccept(resp -> { System.out.println(new Gson().toJson(resp)); }).exceptionally(throwable -> { // Handling exceptions System.out.println(throwable.getMessage()); return null; });*/ // Finally, close the client client.close(); } }
再參照簡訊服務_SDK中心-阿里雲OpenAPI開發者門戶 (aliyun.com)
完成自己的工具類
package com.share.viedo_app.util; import com.aliyun.dysmsapi20170525.Client; import com.aliyun.dysmsapi20170525.models.SendSmsRequest; import com.aliyun.dysmsapi20170525.models.SendSmsResponse; import com.aliyun.teaopenapi.models.Config; import com.google.gson.Gson; public class AliMes { public boolean sendMes(String phone,String code) { try { Config config=new Config() .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")) // 必填,請確保程式碼執行環境設定了環境變數 ALIBABA_CLOUD_ACCESS_KEY_SECRET。 .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); System.out.println(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")); config.endpoint = "dysmsapi.aliyuncs.com"; Client client=new Client(config); SendSmsRequest request=new SendSmsRequest(); request.phoneNumbers=phone; request.signName=""; request.templateCode=""; request.templateParam="{\"code\":\""+code+"\"}"; SendSmsResponse response=client.sendSms(request); if(response.getBody().code!=null&&response.getBody().code.equals("OK")) { return true; } else { return false; } }catch (Exception e) { System.out.println(e); return false; } } }
最後呼叫就收到傳送簡訊了