Android mobile Development Study Notes (2) magical Web APIs

Source: Internet
Author: User

Android mobile Development Study Notes (2) magical Web APIs

I will explain Web APIs in two major directions. 1. How to Implement Web APIs? 2. How does the Android client call Web APIs? What is Web Api? What are the advantages and disadvantages? Why use WebApi instead of Webservice? These questions will not be answered. Baidu, there are a lot of information about this, so they will not go on.

1. How to Implement WebApi on the web end

(1) how to create a WebApi?

In the previous chapter, we talked about how to use the project. net 4.5. The development tool is Visual Studio 2012. In Visual Studio 2012, create an MVC4 project, select Web API, and then generate the project, as shown in figure 2 and Figure 3, compared with a common MVC project, it inherits ApiController. Then we run the project and enter http: // localhost: 56091/api/values/get? in the browser? Id = 5, 4, indicating that the Get Method Instance written by the project by default is successfully called. If data is returned, the call is successful!

(Figure 1)

(Figure 2)

(Figure 3)

(Figure 4)

(2) Get and Post data?

(2.1) Get Method

What is Get? It will not be too long. You can view it on Baidu and use the [HttpGet] logo. Of course, you don't need to add it. You only need to start the method name with Get, the Get method is passed using Url parameters and cannot receive object parameters, such as http: // localhost: 56091/api/values/get? Id = 5. id is a parameter. Of course, multiple parameters can be used, such as http: // localhost: 56091/api/values/get? Id = 5 & name = tim. The default parameter is [FromUri].

Get has a length limit and cannot contain too many parameters. Besides, the parameters are exposed and can be easily intercepted.

(2.2) Post Method

If you use the [HttpPost] method, you do not need to add it. You only need to use the method name to start with Post. The Post method can use Url to pass parameters, or use Body to pass parameters, the default parameter uses [FromUri]. You can add [FromBody] to receive the parameters passed in the body. However, the problem is that I use the [FromBody] method and the parameter is null, A lot of people encounter problems because they don't know if it is a problem with the Web Api itself. Instead, they have to use the most primitive method below to get the Body value.

HttpContextBase context = (HttpContextBase) Request. properties [MS_HttpContext]; // obtain the traditional context HttpRequestBase request = context. request; // define the traditional request object string name = request. form. keys [0]; if (name = null) {name = request. form [0];}

In addition, the Post method cannot directly obtain data from the address in the browser, which is not very convenient for debugging. Therefore, a tool is used. Firefox can install a plug-in called Poster, as shown in figure 6, it is easy to test.

 

(Figure 5)

(Figure 6)

(3) What is the Json data format?

JSON (JavaScript Object Notation) is a lightweight data exchange format that is easy to read and write, and easy to parse and generate by machines.

Json data format transmission is currently the mainstream interface data transmission. In this project, we also use Json format data. All our interface parameters are uniform parameter names followed by Json format strings, for example, http: // localhost: 8010/api/MobileInfo/Get_Welcome? Params = JsonString. This is an interface call, and the returned result is also in Json format.

As shown in figure 7, the Newtonsoft. Json class library is the class library integrated with the VS project. You can easily use the JsonConvert. SerializeObject (value) method to convert the object to the Json format.

(Figure 7)

// Step 2: parameter deserialization T transferObj = default (T); transferObj = Newtonsoft. Json. JsonConvert. DeserializeObject
 
  
(JsonString );
 

 

(4) Route Configuration

As shown in figure 8, the default route configuration is as follows. Only the Controller is found and the address is not allocated according to the Action. Therefore, only the Get method or Post method is found under the same Controller, whether your method name is the same or not, this obviously cannot meet our needs. If you want to identify the address with Action, use the following code to configure it:

config.Routes.MapHttpRoute(    name: CommonApi,    routeTemplate: api/{controller}/{action}/{id},    defaults: new { id = RouteParameter.Optional });

 

(Figure 8)

 

2. How to call WebApi on Android

(1) Call the Get method of web Api

Public void getAnnouncement (final Object reqTag, final WSAnnouncementListCb cb) {// Url parameters requiring WebApi calls are encoded in UTF-8 String url = Constants. WEB_BASE_URL + MobileInfo/tags? JsonString = + Utils. getEncodingParamsString (Object) UserManager. getInstance (). getLoginedUserInfo (); // use the Request object to Request data Mdthod. get WsAnnouncementListRsp. class Object entity class GsonRequest for receiving results
 
  
GsonRequest = new GsonRequest
  
   
(Method. GET, url, WSAnnouncementListRsp. class, new Response. Listener
   
    
() {@ Override public void onResponse (WSAnnouncementListRsp rsp) {// returned Json format data, deserialized object entity if (cb! = Null) {cb. onResponse (Utils. stringToInteger (rsp. message. resultCode), rsp) ;}}, errorListener (true); gsonRequest. setRequestTag (reqTag); RequestManager. addRequest (gsonRequest, reqTag );}
   
  
 

Android deserialization Json method:

Of course, the following code includes checking whether the Token expires and then logging on again after it expires, because determining whether the Token expires is something that every App interface may consider, so it is not deleted, for your reference.

// Response, the parsed object protected Response is returned.
 
  
ParseNetworkResponse (NetworkResponse response) {try {// The received Json format data String json = new String (response. data, HttpHeaderParser. parseCharset (response. headers); // if there is an escape character, replace it with json = json. substring (1, json. length ()-1); json = json. replace (\,); Log. I (L, Response type: + mClazz. getName () + Parsed Json Buffer: + json); // deserialization of Json data WSBaseResponse baseResponse = (WSBaseResponse) mGson. fromJson (json, MClazz); // determines whether the Token has expired 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. getInstance (). 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 {// return the 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) call the Post method of web Api

The Method put in the Url is called like the Get Method. When passing the parameter, change Method. Get to Method. Post,

Therefore, we mainly focus on the Post Body method.

Public void updateUserInfo (final Object reqTag, final WSUpdateUserInfoReq req, final WSUpdateUserInfoCb cb) {setUserIdAndTokenForReq (req); // post Url without any parameter String url = Constants. WEB_BASE_URL + MobileInfo/Save_EmployeeInfo; // req is the parameter GsonRequest
 
  
GsonRequest = new GsonRequest
  
   
(Method. POST, url, Utils. getEncodingParamsString (Object) req), WSCommonRsp. class, null, new Response. Listener
   
    
() {@ 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 call method of the interface in Android. I provide some pseudo code, mainly to explain the function implementation ideas and what important class methods are used. In the next chapter, we will officially learn about Android development and learn how to quickly get started with development by a basic novice.

 

 

 

 

 

 

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.