. NET programmer for Android Learning 4: Using xutils Get post data

Source: Internet
Author: User

Before using some network to find the class for network access, and later found that the Android development has a Chinese class library xutils more comprehensive, but also more classic, so the subsequent use of Xutils class library to record.

In this case, WCF is used by the server to write the WCF service side in: http://www.cnblogs.com/madyina/p/3454741.html Download deployment

The service description is as follows:

All 4 public methods return a user object, where the last one also receives a user object.

Let's request these 4 resources separately.

First step: Implement the interface

Using a relative layout, place 2 buttons, respectively, "Get test" and "Post test".

Layout code such as:

       <ButtonAndroid:id= "@+id/btn_get"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Get Test"Android:onclick= "Btn_gettest"        />            <ButtonAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_torightof= "@+id/btn_get"Android:text= "Post Test"Android:onclick= "Btn_posttest"        />

Step two: Introduce a third-party jar package:

Download the Xutils package and the Fastjson package at the following address, respectively:

Https://github.com/wyouflf/xUtils/blob/master/xUtils-2.6.14.jar
http://repo1.maven.org/maven2/com/alibaba/fastjson/

Copied into eclipse.

But this fastjson bag is really a bit too big, hope to be able to streamline some.

Then join the network access rights:

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

In the Bin\androidmanifest.xml

Step three: Implement network get mode access

The first method in a service is:

[OperationContract] [WebInvoke (UriTemplate="Getperson", Requestformat = Webmessageformat.json, Responseformat = Webmessageformat.json, Method ="GET")]         PublicUser GetUser () {return NewUser {age =" A", ID ="001", Name ="Zhangsan" }; }

So use

Http://192.168.1.6/UserService.svc/GetPerson, if the access is successful, the service returns a JSON string

All we have to do is deserialize the returned JSON string into an object and then access the object's properties.

Xutils has packaged and optimized Android network access for us, so it's easier to write access code now:

     Public voidBtn_gettest (View v) {httputils http=Newhttputils (); String URL= "Http://192.168.1.6/UserService.svc/GetPerson"; Requestparams params=NewRequestparams (); Http.send (httpmethod.get, URL, params,NewRequestcallback<string>() {@Override Public voidOnsuccess (responseinfo<string>responseinfo) {User UserInfo=json.parseobject (Responseinfo.result,user.class); Toast.maketext (Getapplicationcontext (),"Request Result:" +userinfo.getname (), Toast.length_short). Show (); } @Override Public voidonfailure (httpexception error, String msg) {Toast.maketext (Getapplicationcontext (),"Access failed" +msg, Toast.length_short). Show ();    }         }); }

Send to virtual machine running effects such as:

Get method to add parameters just add in the URL, so the second method no longer an example.

Fourth step: Implement network post mode access

The Post method is less than the case, we have a direct view of the body. The idea is to serialize the local object into a JSON string, post to the service, and deserialize the returned data again, as shown in the example above to show the properties of the object.

Service methods such as:

[OperationContract] [WebInvoke (UriTemplate="Getpersonpostbyid", Requestformat = Webmessageformat.json, Responseformat = Webmessageformat.json, Method ="POST")]         PublicUser Getuserpostbyid (User u) {return NewUser {age =" the", ID ="005", Name ="Laoliu" }; }

This is different because the body format of the transfer is JSON format, so you need to add Content-type in the POST request, the detailed code is as follows:

     Public voidBtn_posttest (View v) {httputils http=Newhttputils (); String URL= "Http://192.168.1.6/UserService.svc/GetPersonPostById"; Requestparams params=NewRequestparams (); /*//Add request parameter Params.addbodyparameter (key, value);*/Params.addheader ("Content-type", "Application/json"); User User=NewUser (); User.setname ("Mady"); User.setage ("1"); User.setid ("123"); String Jsonstr=json.tojsonstring (user); Try{params.setbodyentity (Newstringentity (JSONSTR)); } Catch(unsupportedencodingexception e) {        }http.send (httpmethod.post, URL, params,NewRequestcallback<string>() {@Override Public voidOnsuccess (responseinfo<string>responseinfo) {User UserInfo=json.parseobject (Responseinfo.result,user.class); Toast.maketext (Getapplicationcontext (),"Request Result:" +userinfo.getname (), Toast.length_short). Show (); } @Override Public voidonfailure (httpexception error, String msg) {Toast.maketext (Getapplicationcontext (),"Access failed" +error.fillinstacktrace (), Toast.length_short). Show ();     }         }); }

Send to virtual machine running effects such as:

So we're done using Xutils to simplify network access.

. NET programmer for Android Learning 4: Using xutils Get post data

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.