Android Learning Note: Initiating network HTTP POST operations with HttpClient and Asynctask

Source: Internet
Author: User

1, in the ANDROID4, initiates the network HTTP operation, cannot in the activity event (namely the main thread), must operate in the separate thread.

In addition to the network operation, you need to add the following permissions in the manifest file:

<uses-permission android:name= "Android.permission.INTERNET"/>

2. The code example is given below

public void LoadData () {new asynctask<string, void, string> () {@Overrideprotected string Doinbackground (String ... paramsinput) {String url = "Http://10.0.0.5:8080/examples/action"; list<namevaluepair> params = new arraylist<namevaluepair> ();p Arams.add (New Basicnamevaluepair ("type", Paramsinput[0]));p Arams.add (new Basicnamevaluepair ("id", paramsinput[1]));/* Build HttpPost object */httppost HttpRequest = New HttpPost (URL); String strresult = "Doposterror"; try {HttpClient HttpClient = gethttpclient ();/* Add request parameter to request object */httprequest.setentity ( New Urlencodedformentity (params,http. Utf_8));/* Send the request and wait for the response */httpresponse HttpResponse = Httpclient.execute (HttpRequest);/* If the status code is OK */if ( Httpresponse.getstatusline (). Getstatuscode () = = 200) {/* read return Data */strresult = entityutils.tostring ( Httpresponse.getentity ());} else {strresult = "Error Response:" + httpresponse.getstatusline (). toString ();}} catch (Clientprotocolexception e) {strresult = "Error Response:" + e.getmessage (). toString (); e.printsTacktrace ();} catch (IOException e) {strresult = "Error Response:" + e.getmessage (). toString (); E.printstacktrace ();} catch (Exception e) {strresult = "Error Response:" + e.getmessage (). toString (); E.printstacktrace ();} return strresult;} @Overrideprotected void OnPostExecute (String result) {TextView view = (TextView) Findviewbyid (R.id.resulttext); View.settext (result); Super.onpostexecute (result);}}. Execute ("Query", "1");} Private HttpClient gethttpclient () {///create Httpparams to use to set HTTP parameters (this part is not required) httpparams Httpparams = new Basichttpparams () ;//Set connection timeout and socket timeout, and socket cache size Httpconnectionparams.setconnectiontimeout (httpparams, 20 * 1000); Httpconnectionparams.setsotimeout (Httpparams, 20 * 1000); Httpconnectionparams.setsocketbuffersize (Httpparams, 8192);//Set redirection, default is truehttpclientparams.setredirecting ( Httpparams, True);//set user agentstring useragent = "mozilla/5.0 (Windows; U Windows NT 5.1; ZH-CN; rv:1.9.2) gecko/20100115 firefox/3.6 "; Httpprotocolparams.setuseragent (Httpparams, UseragENT);//Create a HttpClient instance//Note HttpClient HttpClient = new HttpClient (); Is the usage in Commons httpclient//, we need to use Apache's default implementation defaulthttpclienthttpclient HttpClient = new Defaulthttpclie in Android 1.5 NT (httpparams); return httpClient;}

In the LoadData method of the preceding code, create a Asynctask object that initiates a network operation in the Doinbackground method of the object, obtaining the result of the operation. Then, in the OnPostExecute method, update the interface with the results obtained earlier.

The network operation here is mainly using httpclient and other related APIs, located under Org.apache.http.client.HttpClient.

Android Learning Note: Initiating network HTTP POST operations with HttpClient and Asynctask

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.