Java servlet mobile App Access Interface (ii) SMS authentication _java

Source: Internet
Author: User
Tags finally block flush md5 encryption readline

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

First, HttpRequest method of request

He gave the Domo in fact has encapsulated a good method, is to use httpclient request, previously in. NET has used this class, and. NET also directly has HttpWebRequest this class, I looked down the code in Java its function should be encapsulated in the URLConnection this class inside, because of time, the encapsulation method I also looked for from the on-line did not study deeply, But it should be a meaning with HttpWebRequest in. Net. The following code, including the demo generation of HttpClient This class of code also affixed.

Package Helper;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;
Import java.io.UnsupportedEncodingException;
Import Java.net.URL;
Import java.net.URLConnection;
Import java.util.List;

Import Java.util.Map;      public class HttpRequest {/** * request to send a GET method to the specified URL * * @param URL * Send the requested URL * @param param *
   Request parameter, the request parameter should be the form of name1=value1&name2=value2.
    * @return The response result of the remote resource represented by the URL/public static string Sendget (string URL, string param) {String results = "";
    
    BufferedReader in = null;
      try {String urlnamestring = URL + '? ' + param;
      URL realurl = new URL (urlnamestring);
      The connection between open and URL urlconnection connection = Realurl.openconnection ();
      Sets the common request attribute Connection.setrequestproperty ("accept", "*/*");
      Connection.setrequestproperty ("Connection", "keep-alive"); Connection.setrequestproperty ("User-agent", "MOZILLA/4.")0 (compatible; MSIE 6.0; Windows NT 5.1;
      SV1) ");
      Establish the actual connection connection.connect ();
      Gets all response header fields Map<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)); }//define BufferedReader input stream to read URL response in = new BufferedReader (New InputStreamReader Connection.getinpu
      Tstream ()));
      String Line;
      while (line = In.readline ())!= null) {result + = line; The catch (Exception e) {System.out.println ("Send GET request exception!
      "+ e);
    E.printstacktrace ();
        ///Use finally block to close the input stream finally {try {if (in!= null) {in.close ();
      } catch (Exception E2) {e2.printstacktrace ();
  } return result; /** * Request * Send the Post method to the specified URL * * @param URL * Send the requested URL * @param param * Request parameters, request parameters should be name1 =value1&nameThe form of 2=value2.
    * The response result of the remote resource represented by the @return/public static string Sendpost (string url, string param) {printwriter out = null;
    BufferedReader in = null;
    String result = "";
      try {URL realurl = new URL (URL);
      The connection between open and URL URLConnection conn = realurl.openconnection ();
      Sets the common request attribute Conn.setrequestproperty ("accept", "*/*");
      Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 6.0; Windows NT 5.1;
      SV1) ");
      The Send POST request must be set to the following two lines conn.setdooutput (true);
      Conn.setdoinput (TRUE);
      Gets the output stream of the URLConnection object = new PrintWriter (Conn.getoutputstream ());
      Send request parameter out.print (param);
      Flush output Stream Buffer Out.flush ();
      Defines the response of the BufferedReader input stream to read the URL in = new BufferedReader (New InputStreamReader (Conn.getinputstream ()));
      String Line;
      while (line = In.readline ())!= null) {  result + = line; The catch (Exception e) {System.out.println ("send POST request exception!)"
      "+e);
    E.printstacktrace ();
        ///Use finally block to turn off output stream, input stream finally{try{if (out!=null) {out.close ();
        } if (In!=null) {in.close ();
      } catch (IOException ex) {ex.printstacktrace ();
    } try {result= new String (Result.getbytes ("iso8859-1"), "UTF-8");
    catch (Unsupportedencodingexception e) {//TODO auto-generated catch block E.printstacktrace ();
  return result;

 }  
}

Second, the official demo httpclient Mode request code

Import Java.io.FileInputStream;

Import java.io.FileNotFoundException;

Import java.io.IOException;
Import org.apache.commons.httpclient.HttpClient;
Import org.apache.commons.httpclient.HttpException;
Import Org.apache.commons.httpclient.NameValuePair;

Import Org.apache.commons.httpclient.methods.PostMethod;  
Import org.dom4j.Document;
Import org.dom4j.DocumentException;  
Import Org.dom4j.DocumentHelper;  

Import org.dom4j.Element; public class Sendsms {private static String Url = ' http://121.199.
  
  
  
  178/webservice/sms.php?method=submit "; 
    public static void Main (String [] args) {httpclient client = new HttpClient (); 
      
    Postmethod method = new Postmethod (URL);    
    Client.getparams (). Setcontentcharset ("GBK");
    Client.getparams (). Setcontentcharset ("UTF-8");

    Method.setrequestheader ("ContentType", "application/x-www-form-urlencoded;charset=utf-8"); String content = new String ("Your verification code is: 7528.") Please do not divulge the verification code to other people. 
    
    "); namevaluepair[] data = {//Submit SMS New Namevaluepair ("Account", "username"), new Namevaluepair ("Password", "password"),//password can use plaintext password or make With 32-bit MD5 encryption//new namevaluepair ("password", util.
    Stringutil.md5encode ("password"), New Namevaluepair ("mobile", "Cell phone number"), New Namevaluepair ("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 ("Short Message submitted successfully"); catch (httpexception e) {//TODO auto-generated catch block E.printstacktrace ();
    catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
    catch (Documentexception e) {//TODO auto-generated catch block E.printstacktrace ();

 }} 0

Third, call the encapsulated HttpRequest code

String  phonemessageparameter=new string ("Account=?&password=wxhdcs@456&content= Your checksum code is: variable.") Please do not leak the check 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, that is, his official documents in the name of the parameter is wrong, issued in the demo is the correct, and his interface is written in webserver, return is not JSON or XML data, but a standard HTML page, Then the required content is written in the HTML tag, if it is the test content text message contents of this parameter must write their provisions, otherwise the error, if the formal purchase can be fixed template version of the content.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.