Java integration Alibaba big fish

Keywords: Programming Java SDK xml Maven

Next, we learned the message service of Alida fish

This article integrates it into the code

1. Use API to send SMS

  • Step 1: view help documents

Ali big fish API

https://help.aliyun.com/product/44282.html?spm=5176.12212976.0.0.15b31cbeK3Pm5Y

  • Step 2: determine the code in Java development

Example demo

https://help.aliyun.com/document_detail/101893.html?spm=a2c4g.11174283.6.651.62c72c42nxOfdH

  • Step 3: search for sendsms

  • Step 4: details of options

2. Use tools to send SMS

  • Step 1: modify the pom.xml file, and add Alibaba big fish SDK dependency
  • Step 2: copy tool class
  • Step 3: call tool class to send SMS

Step 1: modify the pom.xml file, and add Alibaba big fish SDK dependency

Maven coordinates are provided below

	<!--Short message-->
    <dependency>
        <groupId>com.aliyuncs</groupId>
        <artifactId>aliyun-java-sdk-core</artifactId>
    </dependency>
    <dependency>
        <groupId>com.aliyuncs.dysmsapi</groupId>
        <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
    </dependency>

Step 2: copy tool class

	package com.czxy.utils;

	import java.text.SimpleDateFormat;
	import java.util.Date;
	import java.util.Random;

	import com.aliyuncs.DefaultAcsClient;
	import com.aliyuncs.IAcsClient;
	import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
	import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
	import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
	import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
	import com.aliyuncs.exceptions.ClientException;
	import com.aliyuncs.profile.DefaultProfile;
	import com.aliyuncs.profile.IClientProfile;
	/**
	 * Created on 17/6/7.
	 * The DEMO program of SMS API product contains a SmsDemo class in the project, which directly passes the
	 * Execute the main function to experience the API function of the SMS product (just replace AK with AK that has opened the cloud communication SMS product function)
	 * The project relies on two jar packages (stored in the libs directory of the project)
	 * 1:aliyun-java-sdk-core.jar
	 * 2:aliyun-java-sdk-dysmsapi.jar
	 *
	 * Note: UTF-8 is adopted for Demo project coding
	 * Please do not refer to this DEMO for international SMS
	 */
	public class SmsUtil {

		//Product Name: cloud communication short message API product, developers do not need to replace it
		static final String product = "Dysmsapi";
		//Product domain name, developers do not need to replace
		static final String domain = "dysmsapi.aliyuncs.com";

		// TODO here needs to be replaced by the developer's own AK (found on Alibaba cloud access console)
	//    static final String accessKeyId = "LTAIjJJe67SlCCLL";//
	//    static final String accessKeySecret = "B3BZSQDnuUnfZXf22bbovyPaJmCNDt";
		static final String accessKeyId = "LTAIlefATxsjTNoL";//
		static final String accessKeySecret = "zhzDVzH1KjqeZZVOHsTsqfjApi0HJJ";

		public static SendSmsResponse sendSms(String telephone,String name, String code ,String address , String phone) throws ClientException {

			//Self adjustable timeout
			System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
			System.setProperty("sun.net.client.defaultReadTimeout", "10000");

			//Initialization of acsClient, region is not supported temporarily
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
			IAcsClient acsClient = new DefaultAcsClient(profile);

			//Assembly request object - for details, please refer to the console - Documentation section
			SendSmsRequest request = new SendSmsRequest();
			//Required: mobile number to be sent
			request.setPhoneNumbers(telephone); 		//15000000000
			//Required: SMS signature - can be found in SMS console
			request.setSignName("Uncle Tong, old driver");			//Old yuan a washing feet 6
			//Required: SMS template - can be found in SMS console
			request.setTemplateCode("SMS_130929218"); 	//SMS_85550034
			//Optional: the variables in the template replace the JSON string. For example, when the template content is "Dear ${name}, and your verification code is ${code}", the value here is
			//Hello ${name}, please take the item code: ${code}, go to ${address} to pick up the item. If you have any questions, please consult ${phone}.
			request.setTemplateParam("{\"name\":\""+name+"\",\"code\":\""+code+"\",\"address\":\""+address+"\",\"phone\":\""+phone+"\"}");

			//Optional - uplink SMS extension code (please ignore this field for users without special requirements)
			//request.setSmsUpExtendCode("90997");

			//Optional: outId is the extension field provided to the business party, which will be brought back to the caller in the SMS receipt message
			request.setOutId("yourOutId");

			//hint an exception may be thrown here. Pay attention to catch
			SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

			return sendSmsResponse;
		}


		public static QuerySendDetailsResponse querySendDetails(String bizId) throws ClientException {

			//Self adjustable timeout
			System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
			System.setProperty("sun.net.client.defaultReadTimeout", "10000");

			//Initialization of acsClient, region is not supported temporarily
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
			IAcsClient acsClient = new DefaultAcsClient(profile);

			//Assemble request object
			QuerySendDetailsRequest request = new QuerySendDetailsRequest();
			//Required - number
			request.setPhoneNumber("15151772559");
			//Optional - serial number
			request.setBizId(bizId);
			//Required - send date supports query within 30 days, format yyyyMMdd
			SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
			request.setSendDate(ft.format(new Date()));
			//Required - page size
			request.setPageSize(10L);
			//Required - the current page number is counted from 1
			request.setCurrentPage(1L);

			//hint an exception may be thrown here. Pay attention to catch
			QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);

			return querySendDetailsResponse;
		}


		public static void main(String[] args) throws ClientException, InterruptedException {
			/**Generate verification code*/
			//String snumber = RandomStringUtils.random(4); / / there is a bug
			String number = getNumber();
			/**Phone number sent*/
			String telephone = "13699282444";
			//Send message
			SendSmsResponse response = sendSms(telephone,"Mr. Zhang", number , "Shanghai Garden" ,"110");
			System.out.println("Data returned by SMS interface----------------");
			System.out.println("Code=" + response.getCode());
			System.out.println("Message=" + response.getMessage());
			System.out.println("RequestId=" + response.getRequestId());
			System.out.println("BizId=" + response.getBizId());

			Thread.sleep(3000L);

			//Check details
			if(response.getCode() != null && response.getCode().equals("OK")) {
				QuerySendDetailsResponse querySendDetailsResponse = querySendDetails(response.getBizId());
				System.out.println("Data returned from SMS details query interface----------------");
				System.out.println("Code=" + querySendDetailsResponse.getCode());
				System.out.println("Message=" + querySendDetailsResponse.getMessage());
				int i = 0;
				for(QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs())
				{
					System.out.println("SmsSendDetailDTO["+i+"]:");
					System.out.println("Content=" + smsSendDetailDTO.getContent());
					System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
					System.out.println("OutId=" + smsSendDetailDTO.getOutId());
					System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
					System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
					System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
					System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
					System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
				}
				System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount());
				System.out.println("RequestId=" + querySendDetailsResponse.getRequestId());
			}

		}
		/** Random generation of 4-bit verification code*/
		public static String getNumber(){
			int number;//Define two variables
			Random ne = new Random();//Instantiate a random object ne
			number = ne.nextInt(9999-1000+1)+1000;//Assign random values to variables 1000-9999
			System.out.println("The resulting random number is:"+number);//output
			return String.valueOf(number);
		}
	}

Special attention is needed here

First, AccessKey in tool class needs to obtain its own exclusive AK value

  • AK view

Second, the relevant parameters in the method need to be modified to their own (Signature...)

Summary: the following changes are needed to connect here
 1.accessKeyId and accessKeySecret
 2. SMS signature and SMS code of SMS signature 
3. Finally, delete unnecessary variable values according to the template content

Step 3: call tool class to send SMS

The test here is OK. If you connect to the front end with ajax, the verification request will send a message successfully

All kinds of problems are inevitable in the development stage. Here, we will present you SMS interface error status code for self solving

Click to: SMS interface error calling code

Click to: SMS sending status receipt error code

If this article is helpful to you, please enjoy it~

Posted by jabba_29 on Fri, 27 Mar 2020 03:57:42 -0700