Android Practice--http client programming GET request

Source: Internet
Author: User

Android Http Client Programming get

Speaking of HTTP programming, do not remember the GET and post two request methods, this article with simple and clear steps and instructions, the use of Android in the common HTTP programming methods, to the first on the Android road to start the reference and guidance of the struggling people, Colleagues who want to quickly get started with Android HTTP programming can bypass the following passage first.

Before we do one thing, can we stop to think about what we need to do, what we have to do, and then accumulate the template ideas and steps in our experience, often using design patterns in the programming world to summarize these well-done solutions. With these summary accumulation, so that we can extrapolate, in the face of new problems no longer at a loss, this is a good programmer must develop the ability, so every hobby programmers have the responsibility to make themselves a good programmer programmer.

Android Http Client Programming design mode (STEP):

1. Network permissions: add Internet User rights.
2.UI Design: Design user interface.
3. Make a request: the client submits the HTTP request and submits the data, remembering that it cannot be done on the UI thread.
4. Receive response: Receive server-side response, get the server return data.
5.UI Update: client Business processing, updating UI.

This mode is my beginner Android to summarize their own set of patterns, this can help me when it comes to HTTP programming can write good work code, welcome colleagues to give valuable advice. The following is the implementation of HTTP programming practices based on this set of patterns.

1. Network permissions, add user rights:

    <uses-permission android:name= "Android.permission.INTERNET"/>
2.UI design, landing interface UI, text box *1+ Password box *1+ button *1,ui simpler, layout file content slightly, this is written in Chinese, there will be a Chinese garbled problem, in order to simplify the length, Here EditText and button text directly written, this is a very bad coding habits, it is strongly recommended to pull out in practice, defined in the String.xml, as a mirror.

<    LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_parent" android:layout_height= "match_parent" android:orientation= "vertical" > <edittext android:id= "@+id/et_use         Rname "android:layout_width=" match_parent "android:layout_height=" wrap_content "android:hint=" Please enter user name " android:text= "Shan"/> <edittext android:id= "@+id/et_password" android:layout_width= "Match_p"        Arent "android:layout_height=" wrap_content "android:hint=" Please enter the password "android:inputtype=" Textpassword " android:text= "/> <button android:layout_width=" match_parent "android:layout_height=" Wrap_c Ontent "android:onclick=" Loginbyget "android:text=" Get Landed "/></LINEARLAYOUT> 
3. Make a request:write the client HTTP request, and submit the data, the Chinese user name needs to be URL encoded, see Code. ( This step cannot be done on the UI thread )

4. Receive the response: receives the server-side response, and gets the response input stream after the request succeeds. ( This step cannot be done on the UI thread )

public static final String Url_prefix = "Http://191.168.2.177:8080/LoginServer/LoginServlet";/** * Get method Submit request,  This method can only be called on non-UI threads * * @param userName * @param password * @return */public static string Loginbyget (string userName, String Password) {try {//encode Chinese string path = Url_prefix + "? user=" + Urlencoder.encode (userName, "UTF-8") + "&pass=" + Urlen Coder.encode (password, "UTF-8"); URL url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET"); conn.setconnecttimeout, int code = Conn.getresponsecode (), if (code = =) {InputStream is = Conn.getinputstream (); Return Readstream (IS);}} catch (Exception e) {e.printstacktrace ();} return null;} /** * Read data in stream * * @param is * @return */public static String Readstream (InputStream is) {Bytearrayoutputstream BAOs = new Bytearrayoutputstream (); byte[] values = new Byte[1024];try {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 "Parse Failed";}}
5.UI Update: After the parsing server responds to the input stream data, the data content toast is displayed, and the Runonuithread method in the activity class in Android is used appropriately Can simplify the programming of handler.
public void Loginbyget (view view) {final string userName = Etusername.gettext (). toString (); final string password = ETPASSW Ord.gettext (). toString (); if (Textutils.isempty (userName) | | Textutils.isempty (password)) {Toast.maketext (this, "User name or password cannot be empty", Toast.length_long). Show (); return;} Executorservice Executorservice = Executors.newsinglethreadexecutor (); Executorservice.execute (new Runnable () {@ overridepublic void Run () {//Call method in Loginservice final String result = Loginservice.loginbyget (Username,password);/* * This method makes it easy to update the UI, and if the current thread is the UI thread, it will be executed immediately, otherwise it will be placed in the UI thread's event queue Runs the * specified action on the UI thread. If the current thread was * The UI thread, then the action is executed immediately. IF * The current thread was not the UI thread, the action was 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, there has been some thinking and summary of your HTTP programming, when we want to implement the HTTP client, only need to remember the simple design pattern of the five steps, this is just a simple GET request example, will continue to exit the POST request in this design mode, And the use of some HTTP frameworks, please look forward to.

Article 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.