Java servlet mobile App Access Interface (ii) SMS verification

Source: Internet
Author: User

Today to find a few SMS platform, in fact, the most want to use a sharesdk, using it above the HTTP API SMS function, not only the price is low, and can recharge at least 100RMB, but the audit is too strict, the corresponding app must also integrate their SMS function, and to upload the audit also got more than 20 days, I just want to find a message platform to test it, so it just forget it. Then in Baidu casually in a good SMS platform www.wasun.cn, temporarily feel it is also good, at least it gave the test account to accept the speed of text messages not more than 5 seconds, I looked under the general is 3 seconds or even faster. I'll talk about the method of invoking the SMS interface, and the problems encountered in the middle of the use.

HttpRequest method of Request

He gave the Domo in fact already encapsulated a good method, is the use of HttpClient request, before. NET has used this class, and. NET also directly has HttpWebRequest this class, I saw the code in Java its function should be encapsulated in the URLConnection this class, because of the time, Encapsulation method I'm looking for it from the Internet. Not in-depth research, but should and. NET HttpWebRequest is a meaning. The following code, including the demo generation of the HttpClient this class of code is also affixed together.

 PackageHelper;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.PrintWriter;Importjava.io.UnsupportedEncodingException;ImportJava.net.URL;Importjava.net.URLConnection;Importjava.util.List;ImportJava.util.Map; Public classHttpRequest {/*** A request to send a GET method to a specified URL *@paramURL * URL to send request *@paramparam * Request parameters, request parameters should be in the form of name1=value1&name2=value2. * @returnThe response result of the remote resource represented by the URL*/     Public Staticstring sendget (string url, string param) {string result= ""; BufferedReader in=NULL; Try{String urlnamestring= URL + "?" +param; URL Realurl=NewURL (urlnamestring); //opening and linking between URLsURLConnection connection =realurl.openconnection (); //to set common request propertiesConnection.setrequestproperty ("Accept", "*/*"); Connection.setrequestproperty ("Connection", "keep-alive"); Connection.setrequestproperty ("User-agent",                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) "); //establish an actual connectionConnection.connect (); //Get all response header fieldsmap<string, list<string>> map =Connection.getheaderfields (); //iterate through all the response header fields             for(String key:map.keySet ()) {System.out.println (key+ "--->" +Map.get (key)); }            //defines the response of the BufferedReader input stream to read the URLin =NewBufferedReader (NewInputStreamReader (Connection.getinputstream ()));            String Line;  while(line = In.readline ())! =NULL) {result+=Line ; }        } Catch(Exception e) {System.out.println ("Send GET request exception!" " +e);        E.printstacktrace (); }        //Use the finally block to close the input stream        finally {            Try {                if(In! =NULL) {in.close (); }            } Catch(Exception E2) {e2.printstacktrace (); }        }        returnresult; }    /*** Request to send the Post method to the specified URL * *@paramURL * URL to send request *@paramparam * Request parameters, request parameters should be in the form of name1=value1&name2=value2. * @returnThe response result of the remote resource represented*/     Public Staticstring sendpost (string url, string param) {PrintWriter out=NULL; BufferedReader in=NULL; String result= ""; Try{URL Realurl=Newurl (URL); //opening and linking between URLsURLConnection conn =realurl.openconnection (); //to set common request propertiesConn.setrequestproperty ("Accept", "*/*"); Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("User-agent",                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) "); //to send a POST request, you must set the following two linesConn.setdooutput (true); Conn.setdoinput (true); //gets the output stream corresponding to the URLConnection objectout =NewPrintWriter (Conn.getoutputstream ()); //Send Request Parametersout.print (param); //buffer for flush output streamOut.flush (); //defines the response of the BufferedReader input stream to read the URLin =NewBufferedReader (NewInputStreamReader (Conn.getinputstream ()));            String Line;  while(line = In.readline ())! =NULL) {result+=Line ; }        } Catch(Exception e) {System.out.println ("Send POST Request exception!" "+e);        E.printstacktrace (); }        //Use the finally block to close the output stream, input stream        finally{            Try{                if(out!=NULL) {out.close (); }                if(in!=NULL) {in.close (); }            }            Catch(IOException ex) {ex.printstacktrace (); }        }               Try{result=NewString (Result.getbytes ("iso8859-1"), "UTF-8"); } Catch(unsupportedencodingexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        returnresult; }    }

Second, the official demo httpclient Way Request code

//import Java.io.FileInputStream;//import java.io.FileNotFoundException;Importjava.io.IOException;Importorg.apache.commons.httpclient.HttpClient;Importorg.apache.commons.httpclient.HttpException;ImportOrg.apache.commons.httpclient.NameValuePair;ImportOrg.apache.commons.httpclient.methods.PostMethod;Importorg.dom4j.Document; Importorg.dom4j.DocumentException;ImportOrg.dom4j.DocumentHelper; Importorg.dom4j.Element;  Public classsendsms {Private StaticString Url = "Http://121.199.?.178/webservice/sms.php?method=Submit";  Public Static voidmain (String [] args) {HttpClient client=NewHttpClient (); Postmethod Method=NewPostmethod (URL); //client.getparams (). Setcontentcharset ("GBK"); Client.getparams (). Setcontentcharset ("UTF-8"); Method.setrequestheader ("ContentType", "Application/x-www-form-urlencoded;charset=utf-8"); String content=NewString ("Your Verification code is: 7528. Please do not divulge the verification code to other people. "); namevaluepair[] Data= {//Submit SMS                NewNamevaluepair ("Account", "username"),                 NewNamevaluepair ("Password", "password"),//passwords can be encrypted using plaintext passwords or using 32-bit MD5//New Namevaluepair ("Password", util. Stringutil.md5encode ("password")),                NewNamevaluepair ("mobile", "Phone number"),                 NewNamevaluepair ("Content", content),};                                Method.setrequestbody (data); Try{Client.executemethod (method); String Submitresult=method.getresponsebodyasstring (); //System.out.println (submitresult);Document Doc=Documenthelper.parsetext (Submitresult); Element Root=doc.getrootelement (); String Code= Root.elementtext ("code"); String msg= Root.elementtext ("msg")); String Smsid= Root.elementtext ("Smsid");            SYSTEM.OUT.PRINTLN (code);            SYSTEM.OUT.PRINTLN (msg);                                    System.out.println (SMSID); if(Code = = "2") {System.out.println ("Text Message submitted successfully"); }                    } Catch(HttpException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(documentexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }                }    }

Third, call the encapsulated HttpRequest code

String   phonemessageparameter=new string ("Account=?&[email protected]&content= Your check code is:" Variable. Please do not divulge the verification code to other people. &mobile=?&stime=2012-08-01%208:20:23&sign=?&type=pt&extno= "); String returnresult=httprequest.sendpost ("http://121.?. 16.178/webservice/sms.php?method=submit ", phonemessageparameter);   Out.println ("<script> alert (" +returnresult+ ");</script>");

If you use this platform to pay attention to, is his official document in the parameter name is wrong, the demo is correct, and his interface is written in webserver, the return is not JSON or XML data, but a standard HTML page, Then the required content is written in the HTML tags, if it is testing content text message contents This parameter must write their rules, otherwise error, if the official purchase can self-template content.

Java servlet mobile App Access Interface (ii) SMS verification

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.