Android practice -- GET for Android Http client Programming

Source: Internet
Author: User

GET for Android Http client Programming

Speaking of Http programming, I don't have to remember the GET and POST request methods. This article lists the common Http programming methods in Android with simple steps and instructions, for the reference and guidance of those who have just started on the Android Road, colleagues who want to quickly get started with Android Http programming can bypass the following section.

Before doing one thing, can we stop and think about what we need to do, and accumulate the template ideas and steps in our experience, in the programming world, design patterns are usually used to summarize these well-working solutions. With these summary and accumulation, we will be able to draw inferences from each other, and we will not be at a loss in the face of new problems. This is a capability that a good programmer must develop.Hobby ProgrammingColleagues have the responsibility to make themselves a good programmer.

Android Http client programming design mode (STEP ):

1. Network permissions:Add INTERNET user permissions.
2. uidesign:Design the user interface.
3. Send a request:The client submits an HTTP request and data. Remember that the request cannot be completed in the UI thread.
4. Receive response:Receives the response from the server and obtains the data returned by the server.
5. UI update:Client Service Processing and UI update.

This mode is a set of methods that I have learned from Android. This helps me compile code for good work when it comes to HTTP programming. I welcome my colleagues to give valuable comments. The following is an HTTP programming practice based on this mode.

1. Network permissions,Add User Permissions:

    
 
2. uidesign,The UI of the login interface, text box * 1 + Password box * 1 + button * 1, UI is relatively simple, layout file content is omitted, the reason why this is written in Chinese, there will be a Chinese garbled problem, in order to simplify the length, the EditText and Button Text are written directly here, which is a bad coding habit. We strongly recommend that you extract it from the string. xml.

     
      
      
  
 
3. Send a request:Write the HTTP request from the client and submit the data. The Chinese user name must be URL encoded. For details, see the code. (This step cannot be performed in the UI thread)

4. Receive response:Receives the response from the server and obtains the response input stream after the request is successful. (This step cannot be performed in the UI thread)

Public static final String URL_PREFIX = "http: // 191.168.2.177: 8080/LoginServer/LoginServlet";/*** Get request, this method can only be called in a non-UI thread ** @ param userName * @ param password * @ return */public static String loginByGet (String userName, String password) {try {// encode the Chinese character String path = URL_PREFIX + "? User = "+ URLEncoder. encode (userName, "UTF-8") + "& pass =" + URLEncoder. encode (password, "UTF-8"); URL url = new URL (path); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setRequestMethod ("GET"); conn. setConnectTimeout (5000); int code = conn. getResponseCode (); if (code = 200) {InputStream is = conn. getInputStream (); return readStream (is) ;}} catch (Exception e) {e. printStackTrace ();} r Eturn null;}/*** read data in the stream ** @ param is * @ return */public static String readStream (InputStream is) {ByteArrayOutputStream baos = new ByteArrayOutputStream (); byte [] values = new byte [1024]; try {int length = 0; while (length = is. read (values ))! =-1) {baos. write (values, 0, length);} return new String (baos. toByteArray ();} finally {if (baos! = Null) {baos. close ();} if (is! = Null) {is. close () ;}} catch (IOException e) {e. printStackTrace (); return "resolution failed ";}}
5. UI update:After parsing the server's response to the input stream data, the data content Toast is displayed. The runOnUiThread method in the Activity class in Android can be used properly to simplify Handler programming.
Public void loginByGet (View view) {final String userName = etUserName. getText (). toString (); final String password = etPassword. getText (). toString (); if (TextUtils. isEmpty (userName) | TextUtils. isEmpty (password) {Toast. makeText (this, "the user name or password cannot be blank", Toast. LENGTH_LONG ). show (); return;} ExecutorService executorService = export cute (new Runnable () {@ Overridepublic void run () {// call the method final String result in LoginService = LoginService. loginByGet (userName, password);/** this method can be used to conveniently update the UI. If the current thread is a ui thread, it will be executed immediately, otherwise, it will be placed in the event queue of the UI thread, Runs the * specified action on the UI thread. if the current thread is * the UI thread, then the action is executed immediately. if * the current thread is not the UI thread, the action is posted * to the event queue of the UI thread. */runOnUiThread (new Runnable () {public void run () {Toast. makeText (getApplicationContext (), result + "-------", Toast. LENGTH_LONG ). show () ;}}) ;}}); executorService. shutdown ();}
Through this article, do you have any ideas and conclusions about HTTP programming? When we want to implement the HTTP client, we only need to remember the five steps in the simple design mode, this is just an example of a simple GET request. the post request in this design mode will be exited later and the use of some HTTP frameworks will be coming soon.

Source: http://blog.csdn.net/ysjian_pingcx/article/details/25915047

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.