Java invoke HTTP interface

Source: Internet
Author: User
Tags readline

In recent days because of the project needs, do an access control management. Access information is the source of the wonderful pocket. So we need to call the smart Pocket interface, mainly "Device installation registration interface" and "Key voucher distribution interface."

Because has not done before "Java invoke HTTP Interface" Similar function, so find a lot on the internet, also relatively long. The following code feeling more can be, the use of the process also did not have any problems, so it was recorded down.

The code is as follows:

Package Com.zhang.miaodou;
Import Java.io.BufferedReader;
Import Java.io.DataOutputStream;
Import Java.io.InputStreamReader;
Import java.net.HttpURLConnection;
Import Java.net.URL;

Import Java.net.URLEncoder; public class DemoTest1 {public static final String Get_url = "http://112.4.27.9/mall-back/if_user/store_list?storeId=32
";
	public static final String Post_url = "Http://112.4.27.9/mall-back/if_user/store_list";
    
    Coup test interface public static final String Post_url = "Http://121.40.204.191:8180/mdserver/service/installLock"; /** * Interface calls get/public static void Httpurlconectionget () {try {URL url = new URL (get    _url);
            Converts a string to a URL request address httpurlconnection connection = (httpurlconnection) url.openconnection ();//Open connection Connection.connect ()//Connect session//Get input stream BufferedReader br = new BufferedReader (New InputStreamReader
            (Connection.getinputstream (), "UTF-8"));
          String Line;  StringBuilder sb = new StringBuilder ();
            while (line = Br.readline ())!= null) {//loop read stream Sb.append (line); 
        Br.close ();//Close stream connection.disconnect ();//Disconnect System.out.println (sb.tostring ());
            catch (Exception e) {e.printstacktrace ();
        SYSTEM.OUT.PRINTLN ("Failure!");
            }/** * Interface call POST/public static void Httpurlconnectionpost () {try {
            
            URL url = new URL (post_url);  Converts a URL with the URLConnection connection returned by the open method to a HttpURLConnection connection (identifies the remote object connection referenced by a URL) httpurlconnection connection = (httpurlconnection) Url.openconnection ()//At this point cnnection is just a connection object, set the connection output stream to true in the connection, and the default false (P
            
            OST requests are implicitly transitive parameters in the form of a stream connection.setdooutput (true);
            
            Sets the connection input stream to True connection.setdoinput (true);
           Set the request mode to post Connection.setrequestmethod ("POST");
            
            The POST request cache is set to False connection.setusecaches (false);
            
            Sets whether the HttpURLConnection instance automatically performs a redirection connection.setinstancefollowredirects (true); Sets the properties within the request header (the following is the type of the content set, set to the urlencoded encoded from parameter)//application/x-javascript Text/xml->xml data applicat Ion/x-javascript->json object application/x-www-form-urlencoded-> form data//; Charset=utf-8 must be, otherwise the magic pocket will appear garbled "★★★★★	
            
            "Connection.setrequestproperty" ("Content-type", "application/x-www-form-urlencoded;charset=utf-8"); 
            
            Establish a connection (the request does not start until the Connection.getinputstream () method call is initiated, and the above parameters are set to precede this method) Connection.connect (); Create an input output stream that is used to output the parameters to the connection, (output is the content of the following) DataOutputStream dataout = new Dataoutputstr
            
            EAM (Connection.getoutputstream ()); String App_key = "app_key=" + urlencoder.encode ("4f7bf8c8260124e6e9c6bf094951a111 "," utf-8 ");				Modified "Change to error data to avoid information disclosure" String agt_num = "&agt_num=" + urlencoder.encode ("10111", "utf-8");				Changed to error data to avoid information disclosure "String pid =" &pid= "+ urlencoder.encode (" BLZXA150401111 "," utf-8 ");			Modified "Change to error data to avoid information disclosure" String Departid = "&departid=" + urlencoder.encode ("10007111", "utf-8"); Modified "Change to error data to avoid information disclosure" String install_lock_name = "&install_lock_name=" + Urlencoder.encode ("South Gate", "Utf-8")
            ;
            String install_address = "&install_address=" + urlencoder.encode ("Beijing Breeding New", "Utf-8");
            String Install_gps = "&install_gps=" + urlencoder.encode ("116.350888,40.011001", "utf-8");
            String install_work = "&install_work=" + Urlencoder.encode ("Xiao Li", "Utf-8");
            String install_telete = "&install_telete=" + urlencoder.encode ("13000000000", "utf-8");
            
            String Intall_comm = "&intall_comm=" + urlencoder.encode ("All normal", "utf-8"); PaneType parm = aaa=111&bbb=222&ccc=333&ddd=444 String parm = app_key+ agt_num+ pid+ departid+ Install_lo
            
            ck_name+ install_address+ install_gps+ install_work+ install_telete+ Intall_comm;
            
            Output the parameter to the connection dataout.writebytes (parm);
            Refresh and close the stream Dataout.flush () when the output is complete; Dataout.close (); 
            
Important and easy to ignore steps (close the stream, remember!)
            
            System.out.println (Connection.getresponsecode ()); The connection initiates the request, processes the server response (gets the input stream from the connection and wraps it as BufferedReader) bufferedreader bf = new BufferedReader (New InputStreamReader ( 
            Connection.getinputstream (), "UTF-8"));
            String Line; StringBuilder sb = new StringBuilder ();                Used to store response data//loop read stream, if not at the end while (line = Bf.readline ())!= null) {//
            	Sb.append (Bf.readline ());
            Sb.append (line). Append (System.getproperty ("Line.separator")); } Bf.closE (); 
            Important and easy to ignore steps (close the stream, remember!) Connection.disconnect ();
    
        Destroy the connection System.out.println (Sb.tostring ());
        catch (Exception e) {e.printstacktrace ();
        } public static void Main (string[] args) {//Httpurlconectionget ();
    Httpurlconnectionpost (); }
}


only the Post request method is used, get is not used, so no GET request code is removed to ensure code integrity
return Result:

{
  "status": "Fail", "
  Code": "ERR001",
  "MSG": "Merchant 10111 does not exist"
}


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.