Android Mobile Development Learning Note (ii) Magic Web API

Source: Internet
Author: User
Tags encode string parse error

This time is divided into two general directions to explain the Web api,1, how to implement the Web api?2, how to invoke the Android Web Api? What about the Web API? What are the pros and cons? Why use WEBAPI instead of webservice? These questions are not answered, Baidu a bit, about this information a lot, will not go long-winded.

First, how to implement WEBAPI on the web side

(1) How to create a new WEBAPI?

In the previous chapter, we talked about our project using. NET 4.5, the development tool is Visual Studio 2012, you create a new MVC4 project in Visual Studio 2012, you select the Web API, and then the project builds, as shown in Figure II, figure three, compared to a normal MVC project , it inherits the Apicontroller, then we run the project, in the browser input http://localhost:56091/api/values/get?id=5, four, that is, the successful invocation of the project default write Get method instance, A return of data means that the call was successful!

(Figure I)

(Figure II)

(Figure III)

(Figure IV)

(2) Get and post data?

(2.1) Get method

Specifically what is get is no longer wordy, can own Baidu view, using [HttpGet] logo, of course, you can not add, just need method name with get start, get method is passed by the URL parameter, can not receive entity parameters, such as: http://localhost:56091 /api/values/get?id=5,id is the parameter, of course, can also be multi-parameter, such as: Http://localhost:56091/api/values/get?id=5&name=tim, default parameters using [Fromuri]

Get is a length limit, the parameters can not be too much, and the parameters exposed to the outside, easy to be intercepted by people easily.

(2.2) Post method

Use [HttpPost] way to pass, of course also can not add, only need method name with post, post method can use URL pass parameter, can also pass parameters with body, default parameter use [Fromuri], can add [Frombody] Receive the parameters passed in the body, but the problem is that I use [frombody] method, the parameters are empty, the fundamental reception of fixed values, the Internet to check the data, many people encounter problems, do not know is not the Web API itself problems, but the use of the following the most primitive way, get the body value.

            HttpContextBase context = (httpcontextbase) request.properties["Ms_httpcontext"];//get traditional context            Httprequestbase Request = context. request;//defines the traditional request object            string name = Request. Form.keys[0];            if (name = = null)            {                name = Request. FORM[0];            }

In addition, the method of post can not directly in the browser to hit the address to get data, debugging is not very convenient, so with a tool, Firefox can install a plug-in, called poster, as shown in six, testing is very convenient.

(Figure V)

(Figure VI)

(3) JSON data format?

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy to read and write, and is easy for machine parsing and generation.

JSON data format transmission is currently the mainstream interface data transmission, this time our project is also using JSON format data, all of our interface parameters are uniform parameter names, followed by a JSON format string, such as: http://localhost:8010/api/ Mobileinfo/get_welcome? Params=jsonstring, this is an interface call, and the interface returns the result in JSON format.

As shown in seven, using the Newtonsoft.json class library, which is the class library for the VS Project integration, it is convenient to use the Jsonconvert.serializeobject ("value") method to convert the object objects to JSON format.

(Fig. Seven)

                Step2: Parameter deserialization of                T transferobj = default (t);                Transferobj = newtonsoft.json.jsonconvert.deserializeobject<t> (jsonstring);


(4) configuration of the route

As shown in eight, the default routing configuration is this way, only the controller can be found, not according to the action to assign the address, so the same controller will only find the Get method or Post method, regardless of your method name is the same, it is obviously not enough to meet our needs, If you want to identify an address with an action, configure it with the following code:

Config. Routes.maphttproute (    name: "Commonapi",    routetemplate: "Api/{controller}/{action}/{id}",    defaults: New {id = routeparameter.optional});

(Fig. Eight)

Second, how to call Webapi on the Android side

(1) Call the Get method of the Web API

    public void Getannouncement (final Object reqtag, final WSANNOUNCEMENTLISTCB CB) {//need to call Webapi URL address parameter with UTF-8 Encode String url = constants.web_base_url + "Mobileinfo/get_announcementlist?" Jsonstring= "+ utils.getencodingparamsstring ((Object) usermanager.getinstance (). Get        Logineduserinfo ()); Using the Request object, the object entity class that requests the data Mdthod.get Wsannouncementlistrsp.class receives the result gsonrequest<wsannouncementlistrsp> GsonR                Equest = new gsonrequest<wsannouncementlistrsp> (method.get, URL, Wsannouncementlistrsp.class, New Response.listener<wsannouncementlistrsp> () {@Override public voi                            D onresponse (wsannouncementlistrsp RSP) {//returns the JSON format data after the deserialized object entity if (CB! = null) {                        Cb.onresponse (Utils.stringtointeger (Rsp.message.ResultCode), RSP);          }                    }      }, Errorlistener (true));        Gsonrequest.setrequesttag (Reqtag);    Requestmanager.addrequest (Gsonrequest, Reqtag); }

How to deserialize json from Android:

Of course, the following code contains to determine whether the token expires, after expiration, re-login, because it is possible to determine whether the token expires in each app interface may have to consider things, so it is not deleted for your reference.

 Response, returns the parsed object protected response<t> parsenetworkresponse (Networkresponse Response) {try {//Received The JSON-formatted data string of string json = new String (Response.data, Httpheaderparser.parsecharset (response.headers));//If there is an escape character            Just replace her. JSON = json.substring (1, Json.length ()-1);            JSON = json.replace ("\ \", "");            LOG.I (L, "Response type:" + mclazz.getname () + "parsed JSON Buffer:" + JSON);            Deserialize JSON data wsbaseresponse Baseresponse = (wsbaseresponse) Mgson.fromjson (JSON, mclazz);                Determine if TOKEN expires if (Utils.stringtointeger (baseResponse.message.ResultCode) = = Constants.err_token_invalid) {// LOG.I (L, "Get token Status:" + usermanager.getinstance (). Gettokenstatus ());//if (Usermanager. GetInstance (). Gettokenstatus ()! = Token_status. token_getting) {//LOG.I (L, "Set token Status:" + Token_status. token_expired);//Usermanager.getinstance (). SettoKenstatus (Token_status. token_expired),//} synchronized (Gsonrequest.class) {if (usermanager.ge Tinstance (). Gettokenstatus ()! = Token_status.                                                                   token_getting) {log.i (L, "Relogin ...");                        Requestmanager.addcachedrequest (this);                            Usermanager.getinstance (). Relogin (New Onloginlistener () {@Override public void Onlogin (int result, String message) {if (result = = Usermanager.login_result_ok                                                                        {LOG.I (L, "Login suceesss"); Usermanager.getinstance (). Settokenstatus (Token_status.                                                                                                      TOKEN_OK); } else {log.i (L, "Login failed ..."); Show login Activity usermanager.getinstance (). Settokenstatus (Token_status.                                    Token_fail);                                    Myactivitymanager.getinstance (). finishallactivity ();                                Showloginactivity ();                    }                            }                        });                       } else {//LOG.I (L, "Prepare resend Request");                        Resendrequest ();                    Requestmanager.addcachedrequest (this);            }} return Response.error (New Tokenexpirederror ());                                                         } else {//returns a generic object return Response.success ((T) baseresponse/*                                                   * Mgson.fromjson (JSON, * mclazz)      */, Httpheaderparser.parsecacheheaders (response));            }} catch (Unsupportedencodingexception e) {log.e (L, "Response Parse Error:" + mclazz.getname ());        Return Response.error (New ParseError (e));            } catch (Jsonsyntaxexception e) {log.e (L, "Response Parse Error:" + mclazz.getname ());        Return Response.error (New ParseError (e)); }    }


(2) Calling the Post method of the Web API

In the URL of the same as the Get method to invoke, but only when the reference, the Method.get changed to Method.post mode,

So the body method that mainly speaks of post

public void Updateuserinfo (final Object Reqtag, final wsupdateuserinforeq req, final WSUPDATEUSERINFOCB CB) {        Setuseridandtokenforreq (req); The post URL does not take any parameters String URL = constants.web_base_url + "Mobileinfo/save_employeeinfo";//req is the parameter gsonrequest& Lt wscommonrsp> gsonrequest = new Gsonrequest<wscommonrsp> (Method.post, URL,UTILS.GETENCODINGPARAMSS                    Tring ((Object) req), Wscommonrsp.class, NULL, new response.listener<wscommonrsp> () {                            @Override public void Onresponse (WSCOMMONRSP rsp) {if (CB! = null) {                        Cb.onresponse (Utils.stringtointeger (Rsp.message.ResultCode), RSP);        }}}, Errorlistener (true));        Gsonrequest.setrequesttag (Reqtag);    Requestmanager.addrequest (Gsonrequest, Reqtag); }


The above is the implementation of the app interface and the interface in Android call method, I provide a number of pseudo-code, mainly to explain the idea of the implementation of the function and the use of important class methods. The next chapter of the formal study of Android development, see a 0 basic novice how to quickly get started to do development.

Next chapter: Everything starts with the HelloWorld


Android Mobile Development Learning Note (ii) Magic Web API

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.