. NET Programmer Android Learning path 3:post data to the Web API

Source: Internet
Author: User
Tags gettext

In this example, we implement a real network interaction, post the data to the API, then receive the server's return value for processing, and introduce custom types and legends of Ali's Fastjson.

Implementation ideas such as:

1. The data of receiving customer post on the API is restored to object, and the output is appended with a suffix for each attribute;

2. Enter the user name and password on the client to compare with the server-side return;

We post to the server is name=mady&pwd=123, the server was added with the suffix Name=madya

&pwd=1231 so our client needs to enter Madya and 1231 to verify success.

The specific operation shows as follows:

First, prepare the API:

The current write API uses the ASP. NET WEB API2. Create an API project in VS2013 and configure him to support JSON first:

Open the Webapiconfig file in your project and include a configuration entry in the Register method:

Config. FORMATTERS.JSONFORMATTER.SUPPORTEDMEDIATYPES.ADD (new mediatypeheadervalue ("text/html "));

Create entity classes such as:

     Public class UserInfo    {        publicstringgetset;}          Public string Get Set ; }    }

Open the Valuescontroller modify code as follows:

        // POST api/values         Public UserInfo Post ([frombody]userinfo value)        {            returnnew"a", pwd = value.pwd+"1 " };        }

You can open Fidder debugging until it succeeds:

Second, the introduction of Ali's Fastjson package

Just right-click to paste in:

This bag really works:

String json=json.tojsonstring (user);   //UserInfo userinfo=json.parseobject (json,userinfo.  Class);    // deserialization

The 2 sentences are all done.

Let's go ahead and create a new Java entity class:

Importjava.io.Serializable; Public classUserInfoImplementsserializable{PrivateString name;PrivateString pwd; PublicString getpwd () {returnpwd;} Public voidsetpwd (String pwd) { This. PWD =pwd;} PublicString GetName () {returnname;} Public voidsetName (String name) { This. Name =name;}}

Then modify the network access class, the last section is too shabby (see attached).

Then modify the async part code:

        protected string Doinbackground (String ... params)        {//                        UserInfo user=new  UserInfo ();            User.setname ("Mady");            User.setpwd ("123");                        String Str_json=json.tojsonstring (user);               return Httputils.sendpostmessage (params[0],str_json);        }

And the completion code:

        protected voidOnPostExecute (String result) {TextView lblinfo=(TextView) Findviewbyid (r.id.form_title); EditText Txt_login_name=(EditText) Findviewbyid (r.id.txt_login_name); EditText Txt_login_pass=(EditText) Findviewbyid (R.ID.TXT_LOGIN_PWD); String LoginName=Txt_login_name.gettext (). toString (). Trim (); String Loginpass=Txt_login_pass.gettext (). toString (). Trim (); UserInfo UserInfo=json.parseobject (Result,userinfo.class); if(Loginpass.equals (Userinfo.getpwd ()) &&loginname.equals (Userinfo.getname ())) {Lblinfo.settext ("Login Successful!" "); }            Else{Lblinfo.settext ("Login failed!" "); }          }

By this completion, there is no change in the unchanged.

Attach the new network access class:

 Public classhttputils{/**     * @paramServer URL address for path request *@paramencode encoded format *@returnconverts the data returned from the server side into a string*/     Public Staticstring Sendpostmessage (String path,string jsonstr) {string result= ""; HttpClient HttpClient=Newdefaulthttpclient (); Try{httppost HttpPost=Newhttppost (path); Httppost.addheader ("Content-type", "Text/json"); Httppost.setentity (Newstringentity (JSONSTR)); HttpResponse HttpResponse=Httpclient.execute (HttpPost); if(Httpresponse.getstatusline (). Getstatuscode () = =HTTPSTATUS.SC_OK) {//log.e ("json+++++2:", jsonstr); Log info for debugHttpentity httpentity =httpresponse.getentity (); if(Httpentity! =NULL) {result= Entityutils.tostring (httpentity, "UTF-8"); }            }        }        Catch(Exception e) {e.printstacktrace (); }        finally{Httpclient.getconnectionmanager (). Shutdown (); }                returnresult; }}

. NET Programmer Android Learning path 3:post data to the Web API

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.