Get and post requests for the Android HttpURLConnection class

Source: Internet
Author: User

1  /**2 * Get method Use3      */4     Private voidHttpGet () {5         NewThread () {6 @Override7              Public voidRun () {
The login here is the parameter after the request address is stitching8String Path = LOGIN + "? phone=12345678900&password=123456";9 URL url;Ten httpurlconnection Connection; One Try { AURL =NewURL (path); -Connection =(HttpURLConnection) url.openconnection (); -Connection.setconnecttimeout (4000);//Set link timeout theConnection.setrequestmethod ("GET");//Set Request method - -Connection.setrequestproperty ("Content-type", "application/x-www-form-urlencoded")///Set the content of the request body, the same as the default is the request is the text content - + intResponsecode =Connection.getresponsecode (); - if(Responsecode = =HTTPURLCONNECTION.HTTP_OK) { +InputStream InputStream =Connection.getinputstream (); A FinalString s =stremtostring (inputstream); at -Runonuithread (NewRunnable () { - @Override - Public voidrun () { -Toast.maketext (mainactivity. This, S, Toast.length_short). Show (); - } in }); - inputstream.close (); to } + -}Catch(Exception e) { the e.printstacktrace (); * } $ }Panax Notoginseng }.start (); -}
1    /**2 * Post Method3      */4     Private voidHttpPost (FinalMap<string, string>prams) {5         NewThread () {6 @Override7              Public voidrun () {8                 if(Prams = =NULL) {9Runonuithread (NewRunnable () {Ten @Override One                          Public voidrun () { AToast.maketext (mainactivity. This, "Missing Parameters!", Toast.length_short). Show (); -                         } -                     }); the                     return; -                 } - URL url; - httpurlconnection Connection; +                 Try { -                     //stitching incoming Request Parameters +StringBuffer buffer =NewStringBuffer (); A                     //read the parameters in the incoming map collection at                      for(Map.entry<string, string>Entry:prams.entrySet ()) { -String key =Entry.getkey (); -String value =Entry.getvalue (); -                         //stitching parameters such as: Phone = 12345678900 & password = 123456 -Buffer.append (key + "=" + Urlencoder.encode (value, "utf-8") + "&"); -                     } in                     //here is the & symbol to remove the end stitching -Buffer.deletecharat (Buffer.length ()-1); to                     //REGISTER is a test request address for my own server +URL =NewURL (REGISTER); -Connection =(HttpURLConnection) url.openconnection (); theConnection.setconnecttimeout (4000); *                      $                     //the output stream here indicates the response output stream of the server to the customer service is InputStreamPanax Notoginseng                     //the input stream here indicates that the customer input data to the server is OutputStream -Connection.setdoinput (true);//gets the response of the server output stream here By default is true can not be set theConnection.setdooutput (true);//The setting allows data to be written to the service and gets the input stream to the server.  +Connection.setrequestmethod ("POST"); A                     //The content requested by the server here requests that the text content is not set by default theConnection.setrequestproperty ("Content-type", "application/x-www-form-urlencoded"); +                     //set the request body length entered to the server -Connection.setrequestproperty ("Content-length", String.valueof (buffer.tostring (). GetBytes (). length); $                     //writing the request body to the server $ Connection.getoutputstream (). Write (Buffer.tostring (). GetBytes ()); -                     //get the request status HTTPURLCONNECTION.HTTP_OK for the request to write successfully 200 can also -                     intResponsecode =Connection.getresponsecode (); the                     if(Responsecode = =HTTPURLCONNECTION.HTTP_OK) { -InputStream InputStream =Connection.getinputstream ();Wuyi                         FinalString result =stremtostring (inputstream); theRunonuithread (NewRunnable () { - @Override Wu                              Public voidrun () { -Toast.maketext (mainactivity. This, result, Toast.length_short). Show (); About                             } $                         }); - inputstream.close (); -                     } -  A}Catch(Exception e) { + e.printstacktrace (); the                 } -             } $ }.start (); the}
1  /**2 * Convert input stream to string3      *4      * @paramInputStream5      * @return6      * @throwsIOException7      */8     PrivateString stremtostring (InputStream inputstream)throwsIOException {9Bytearrayoutputstream BOS =NewBytearrayoutputstream ();Ten         if(InputStream! =NULL) { One             intLen; A             byte[] bytes =New byte[1024]; -              while(len = inputstream.read (bytes))! =-1) { -Bos.write (Bytes, 0, Len); the             } -             returnbos.tostring (); -}Else { -             return""; +         } -}

Finally, the small friends do not understand or unclear can give me a message welcome to give me advice or point out the problem we all need a learning process

Get and post requests for the Android HttpURLConnection class

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.