Java implementation Send SMS

Source: Internet
Author: User
Tags aliyun
Java Implementation send SMS (call Aliyun API in this chapter)

The address is as follows
https://market.aliyun.com/products/56928004/cmapi022659.html?spm=5176.2020520132.101.5.TsClbR#sku=yuncode16659000011

Go to the console and get Appcode.

Tell the merchant your short term template, dynamic content is custom parameters and sellers negotiate



The dependencies required by the MAVEN project

<?xml version= "1.0" encoding= "UTF-8"?> <project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "HTT" P://www.w3.org/2001/xmlschema-instance "xsi:schemalocation=" http://maven.apache.org/POM/4.0.0 Http://maven.apach E.org/xsd/maven-4.0.0.xsd "> <modelVersion>4.0.0</modelVersion> <groupid>com.aliyun.api.gate

    Way</groupid> <artifactId>java.demo</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>com.alibaba</groupId> <a
        Rtifactid>fastjson</artifactid> <version>1.2.15</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactid&gt ;httpclient</artifactid> <version>4.2.1</version> </dependency> <de Pendency> &Lt;groupid>org.apache.httpcomponents</groupid> <artifactId>httpcore</artifactId> <version>4.2.1</version> </dependency> <dependency> <groupid&gt ;commons-lang</groupid> <artifactId>commons-lang</artifactId> <version>2.6 </version> </dependency> <dependency> <groupid>org.eclipse.jetty</g Roupid> <artifactId>jetty-util</artifactId> <version>9.3.7.v20160115</vers
            ion> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.5</version> <scope>test& lt;/scope> </dependency> </dependencies> </project>

Write test code in Testcontroller.java

Import Java.util.HashMap;

Import Java.util.Map;
Import Org.apache.http.HttpResponse;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.beans.factory.annotation.Qualifier;
Import Org.springframework.stereotype.Controller;

Import org.springframework.web.bind.annotation.RequestMapping;
Import com.bjpowernode.beans.Student;

Import Com.bjpowernode.service.IStudentService;
         @Controller @RequestMapping ("/test") public class TestController {@RequestMapping ("/t.do") public void T () {
            String host = "http://yzx.market.alicloudapi.com";
            String Path = "/yzx/sendsms";
            String method = "POST";
            String Appcode = "Fill in your appcode here";
            map<string, string> headers = new hashmap<string, string> (); The last format in the header (the middle is an English space) is Authorization:appcode 83359fd73fe94948385f570e3c139105 headers.put ("Authorization", "
            Appcode "+ appcode); Map<string, string> Querys = new hashmap<string, string> ();
            Querys.put ("mobile", "fill in the phone number you want to send");
            Querys.put ("param", "code:1234");
            Querys.put ("param", "fill in the format of the variable names and variables defined by you and the merchant in a single line of code");
            Querys.put ("tpl_id", "fill in the template for you and the merchant to discuss here");


            map<string, string> bodys = new hashmap<string, string> (); try {/** * Important tips are as follows: * httputils please from * Https://github.com/ali  Yun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/httputils.java * Download * * Corresponding dependencies please refer to * HTTPS://GITHUB.COM/ALIYUN/API-GATEWAY-DEMO-SIGN-JAVA/BL Ob/master/pom.xml */HttpResponse response = httputil.dopost (host, path, method, headers,
                Querys, Bodys);

                System.out.println (Response.tostring ()); Gets the body//system.out.println of the response (EntityutilS.tostring (Response.getentity ()));
            catch (Exception e) {e.printstacktrace (); }
    }
}

Httputil.java Tool Class

Import java.io.UnsupportedEncodingException;
Import Java.net.URLEncoder;
Import java.security.KeyManagementException;
Import java.security.NoSuchAlgorithmException;
Import Java.security.cert.X509Certificate;
Import java.util.ArrayList;
Import java.util.List;

Import Java.util.Map;
Import Javax.net.ssl.SSLContext;
Import Javax.net.ssl.TrustManager;

Import Javax.net.ssl.X509TrustManager;
Import Org.apache.commons.lang.StringUtils;
Import Org.apache.http.HttpResponse;
Import Org.apache.http.NameValuePair;
Import org.apache.http.client.HttpClient;
Import org.apache.http.client.entity.UrlEncodedFormEntity;
Import Org.apache.http.client.methods.HttpDelete;
Import Org.apache.http.client.methods.HttpGet;
Import Org.apache.http.client.methods.HttpPost;
Import Org.apache.http.client.methods.HttpPut;
Import Org.apache.http.conn.ClientConnectionManager;
Import Org.apache.http.conn.scheme.Scheme;
Import Org.apache.http.conn.scheme.SchemeRegistry;
Import Org.apache.http.conn.ssl.SSLSocketFactory; IMport org.apache.http.entity.ByteArrayEntity;
Import org.apache.http.entity.StringEntity;
Import org.apache.http.impl.client.DefaultHttpClient;

Import Org.apache.http.message.BasicNameValuePair; public class Httputil {/** * get * @param host * @param path * @param method * @par AM Headers * @param querys * @return * @throws Exception/public static HttpResponse doget (Strin  G Host, string path, string method, Map<string, string> headers, map<string, string>

        Querys) throws Exception {httpclient httpclient = wrapclient (host);
        HttpGet request = new HttpGet (BuildUrl (host, Path, Querys));
        For (map.entry<string, string> e:headers.entryset ()) {Request.addheader (E.getkey (), E.getvalue ());
    return Httpclient.execute (Request); /** * Post form * * @param host * @param path * @parAm method * @param headers * @param querys * @param bodys * @return * @throws Exception * * public static HttpResponse DoPost (string host, String path, string method, Map<string, string> Heade RS, map<string, string> Querys, map<string, string> bodys) throws Except

        Ion {httpclient httpclient = wrapclient (host);
        HttpPost request = new HttpPost (BuildUrl (host, Path, Querys));
        For (map.entry<string, string> e:headers.entryset ()) {Request.addheader (E.getkey (), E.getvalue ()); } if (Bodys!= null) {list<namevaluepair> namevaluepairlist = new Arraylist<namevalu

            Epair> ();
            For (String Key:bodys.keySet ()) {Namevaluepairlist.add (New Basicnamevaluepair (Key, Bodys.get (key)); } urlencodedformentity formentity = new Urlencodedformentity (namevaluepairlist, "Utf-8"); Formentity.setcontenttype ("application/x-www-form-urlencoded;
            Charset=utf-8 ");
        Request.setentity (formentity);
    return Httpclient.execute (Request);
     /** * Post String * * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception/public static HttpResponse DoP OST (string host, String path, string method, Map<string, string> headers, map<string, S Tring> Querys, String body) throws Exception {httpclient httpclient = Wrapclien

        T (host);
        HttpPost request = new HttpPost (BuildUrl (host, Path, Querys));
        For (map.entry<string, string> e:headers.entryset ()) {Request.addheader (E.getkey (), E.getvalue ()); } if (Stringutils.isnotblank (body)) {request.setentity (new StringentiTy (Body, "utf-8"));
    return Httpclient.execute (Request);
     /** * Post Stream * * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception/public static HttpResponse DoPost (string host, String path, string method, Map<string, string> headers, map<string, Stri Ng> Querys, byte[] body) throws Exception {httpclient httpclient = wrapclient (h

        OST);
        HttpPost request = new HttpPost (BuildUrl (host, Path, Querys));
        For (map.entry<string, string> e:headers.entryset ()) {Request.addheader (E.getkey (), E.getvalue ());
        } if (body!= null) {request.setentity (new bytearrayentity);
    return Httpclient.execute (Request);
    /** * Put String * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */public static HttpResponse DoPut (string host, String path, string method, Map<string, string>      
        Headers, map<string, string> Querys, String body) throws Exception {

        HttpClient httpclient = wrapclient (host);
        Httpput request = new Httpput (BuildUrl (host, Path, Querys));
        For (map.entry<string, string> e:headers.entryset ()) {Request.addheader (E.getkey (), E.getvalue ());
        } if (Stringutils.isnotblank (body)) {request.setentity (the new stringentity (body, "utf-8"));
    return Httpclient.execute (Request); /** * Put stream * @param host * @param path * @param method * @param headers * @para M Querys * @param body * @return * @throws Exception/Public Static HttpResponse DoPut (string host, String path, string method, Map<string, string> headers, Map<string, string> Querys, byte[] body) throws Exception {httpclient HT

        Tpclient = wrapclient (host);
        Httpput request = new Httpput (BuildUrl (host, Path, Querys));
        For (map.entry<string, string> e:headers.entryset ()) {Request.addheader (E.getkey (), E.getvalue ());
        } if (body!= null) {request.setentity (new bytearrayentity);
    return Httpclient.execute (Request); /** * Delete * @param host * @param path * @param method * @param headers * @param querys * @return * @throws Exception/public static HttpResponse Dodelete (string host, String
            Path, String method, map<string, string> headers, map<string, string> Querys) THrows Exception {httpclient httpclient = wrapclient (host);
        Httpdelete request = new Httpdelete (BuildUrl (host, Path, Querys));
        For (map.entry<string, string> e:headers.entryset ()) {Request.addheader (E.getkey (), E.getvalue ());
    return Httpclient.execute (Request); private static string BuildUrl (string host, String path, map<string, string> Querys) throws Unsupportedencodi
        ngexception {StringBuilder Sburl = new StringBuilder ();
        Sburl.append (host); if (!
        Stringutils.isblank (Path)) {sburl.append (path);
            } if (null!= querys) {StringBuilder sbquery = new StringBuilder ();
                    For (map.entry<string, string> query:querys.entrySet ()) {if (0 < Sbquery.length ()) {
                Sbquery.append ("&"); } if (Stringutils.isblank (Query.getkey ()) &&! Stringutils.isblank (qUery.getvalue ())) {Sbquery.append (Query.getvalue ()); } if (!
                    Stringutils.isblank (Query.getkey ())) {Sbquery.append (Query.getkey ()); if (!
                        Stringutils.isblank (Query.getvalue ())) {sbquery.append ("=");
                    Sbquery.append (Urlencoder.encode (Query.getvalue (), "Utf-8")); }} if (0 < Sbquery.length ()) {Sburl.appe nd ("?").
            Append (sbquery);
    } return sburl.tostring ();
        private static HttpClient wrapclient (String host) {httpclient httpclient = new Defaulthttpclient ();
        if (Host.startswith ("https://")) {sslclient (httpclient);
    return httpclient; private static void Sslclient (HttpClient httpclient) {try {sslcontext ctx = Sslcontext.getins Tance ("TLS");
                    X509trustmanager TM = new X509trustmanager () {public x509certificate[] Getacceptedissuers () {
                return null; } public void checkclienttrusted (x509certificate[] xcs, String str) {} p
            ublic void checkservertrusted (x509certificate[] xcs, String str) {}};
            Ctx.init (NULL, new trustmanager[] {TM}, NULL);
            Sslsocketfactory SSF = new Sslsocketfactory (CTX);
            Ssf.sethostnameverifier (Sslsocketfactory.allow_all_hostname_verifier);
            Clientconnectionmanager CCM = Httpclient.getconnectionmanager ();
            Schemeregistry registry = Ccm.getschemeregistry ();
        Registry.register (New Scheme ("https", 443, SSF));
        catch (Keymanagementexception ex) {throw new RuntimeException (ex);
        catch (NoSuchAlgorithmException ex) {throw new RuntimeException (ex);
   } }
} 

Success is as follows

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.