In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Today, I will talk to you about the secret words of data exchange between Android client and server, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.
1. Communication mode between Android client and server
The main modes of communication are HTTP and Socket.
HTTP communication: even if the HTTP protocol is used for communication, the working principle is that the client sends a HTTP request to the server. After receiving the request, the server first parses the request from the client, and then returns the data to the client, and then the client parses and processes the data. The HTTP connection adopts the "request-response" mode, that is, the connection channel is established when the request is made. When the client sends the request like the server, the server can send data to the client. Socket communication: Socket, also known as socket, provides a port to communicate with the outside world within the program, that is, port communication. By establishing a socket connection, a channel can be provided for data transmission between both sides of the communication. The main features of Socket are low data loss rate, easy to use and easy to transplant. Socket is similar to the connection of peer to peer, where one party can speak to the other party at any time.
Summary: both HTTP and Socket are based on the TCP protocol. Two modes of communication are used:
1. In the case of using HTTP: both parties do not need to be connected online at all times, such as obtaining client resources, uploading files, and so on.
two。 UDP usage: most instant messaging applications (QQ, Wechat), chat rooms, Apple APNs, etc.
2. Data interaction between Android client and server
There are three main types:
Data stream
The data from the web server to the mobile terminal is generally packaged in a byte array, which contains different data types. The client takes the way of Java data flow and over-stream to extract various types of data from the byte array.
I used this interaction at the beginning of learning Android, and I didn't find any company using it in the actual project. This method expands the ability of Android platform to parse data when accessing Web server for interaction, and it is only for research and learning.
XML
Standard data format for Webservice.
Protocol Buffers
Protocol Buffers is a lightweight and efficient structured data storage format that supports cross-platform. It is very suitable for data storage or RPC data exchange format. The biggest advantage over JSON is that the data volume can be compressed very small and the transmission efficiency is relatively high. I have never used it in this project.
JSON
JSON (JavaScript Object Notation) is a lightweight data exchange format. Easy for people to read and write. At the same time, it is also easy to parse and generate by machine. There is no doubt that people use it the most.
This article focuses on common formats about json data formats.
The adoption of the json data format, depending on the business situation, is generally a consensus among the team. The iterative update of the technology will basically consider the versatility, portability and readability of multiple platforms in the later stage. For example, our development team has mobile development (Android, iOS), front-end development (H5 development) and background development (golang development).
Let's first take a look at the development specification of the server.
Server development specification we use RESTful,RESTful is the most popular API design specification for the design of web data interface.
3. Why do you want to make RESTful API
Resource-oriented (URI), with interpretation; for (GET / POST / PUT / PATCH / DELETE) and resource (URI) separation, more "lightweight"; simple data description, so that JSON, XML, Protocol Buffers can be fully covered, mainly using JSON
Its core principle is to define named resources that can be manipulated in a small number of ways. Resources and methods can be regarded as nouns and verbs of API.
4. Http request method
GET: read (Read) POST: new (Create) PUT: new (Update), usually all update new PATCH: new (Update), usually partial update new DELETE: delete (Delete)
At the beginning of the project, the client and server generally interact with each other in the way of Get and Post. With the evolution of the business and the specification iteration of the technology, we have to follow the specification in the later stage. Therefore, we use the above methods to design the server interface, and accordingly, the request mode of the mobile terminal has to correspond to it.
At this point, instead of repeating the design specifications of RESTful API, you can learn more about Baidu.
5. Practical application of Json interactive data type
Interface data is generally transmitted in JSON format, but it is important to note that there are only six data types for JSON values:
Number: integer or floating point String: string Boolean:true or false Array: array contained in square braces [] Object: object contained in curly braces {} Null: null type
The data types transferred cannot exceed these six data types, and Date data types cannot be used. Different parsing libraries have different parsing methods, which may lead to exceptions. If you encounter date data, the best way is to use milliseconds to represent the date.
5.1 data types of String
Usage scenario: for example, when a user logs out, he only needs to get the return status and prompt information, and does not need to return any data.
{"code": 1000, "message": "success"}
Data parsing tool class:
Abstract class BaseStringCallback: BaseCallback () {override fun onSuccess (data: String) {val responseData = JSONObject (data) val code = responseData.getInt ("code") val message = responseData.getString ("message") if (code = = 1000) {success (message)} else {/ / other states}} abstract fun success (msg: String)}
When called (pseudo code):
LogoutApi.execute (object: BaseStringCallback () {override fun success (msg: String) {/ / processing data})
5.2 Object data type
The identification mark is: {}
Usage scenario: for example, get the current user information and return the owner entity class, which we can directly convert to the owner entity class using the Gson utility class.
{"code": 1000, "message": "success", "resp": {"owner": {"id": 58180, "name": "Zhang San", "idCert": "", "certType": 1, "modifier": "jun5753", "updateTime": 1567127656436},}}
Convert Json data to entity class utility classes:
Abstract class BaseObjectCallback (privateval clazz: Class): BaseCallback () {override fun onSuccess (data: String) {val responseData = JSONObject (data) val code = responseData.getInt ("code") val message = responseData.getString ("message") if (code = 1000) {val disposable = Observable.just (responseData) .map {it.getJSONObject ("resp"). ToString ()} .map {JsonUtil.parseObject (it, clazz)!} .applyScheduler () .subscribe ({success (it)}) {/ / handling on exception})} else {/ / handling on other states}} abstract fun success (data: t)}
When called (pseudo code):
LaunchApi.getOwerInfo.execute (object: BaseObjectCallback (OwnerEntity::class.java) {override fun success (data: OwnerEntity) {/ / processing data})
5.3. Array data type
The identification mark is: []
Usage scenario: for example, to get a contact list, the data returned is a contact list, such as ArrayList.
{"code": 1000, "message": "success", "resp": {"contact": [{"id": 5819, "name": "coming", "phone": "", "address": "ha", "province": "Hunan Province", "city": "Changsha City", "area": "Furong District", "modifier": "jun5753", "isOwner": 0 "updateTime": 1566461377761}, {"id": 5835, "name": "Primary six", "phone": "13908258239", "address": "Tiananmen Square", "province": "Beijing", "city": "Beijing", "area": "Dongcheng District", "modifier": "jun5753", "isOwner": 0, "updateTime": 1567150580553}
Convert Json data to entity class list utility class:
Abstract class BaseArrayCallback (privateval clazz: Class): BaseCallback () {override fun onSuccess (data: String) {val responseData = JSONObject (data) val code = responseData.getInt ("code") val message = responseData.getString ("message") if (code = 1000) {val disposable = Observable.just (responseData) .map {it.getJSONArray ("resp"). ToString ()} .map {JsonUtil.parseArray (it, clazz)!} .applyScheduler () .subscribe ({success (it)}) {/ / handling on exception})} else {/ / handling on other states}} abstract fun success (data: ArrayList)}
When called (pseudo code):
LaunchApi.getContactList.execute (object: BaseArrayCallback (ContactEntity::class.java) {override fun success (data: ArrayList) {/ / processing data})
5.4 complex data format
Usage scenario: if the user's filtered data needs to be uploaded to the server, get the latest data information from the server every time you enter the filtering interface.
The filtered json data returned is as follows:
{"code": 1000, "message": "success", "resp": {"filterdata": [321,671],}
The data at this time is different from the Json data types mentioned above. There is no key in the returned list, only the value value. Is not returned as a key-value pair (key-value).
Parsing method:
Declare entity classes
Class FilterEntity {/ * * filtered data: parsing array objects as Int data ArrayList * / var filterdata = ArrayList ()}
Call method (pseudo code):
HomeApi.getFilterData () .execute (object: CJJObjectCallback (FilterEntity::class.java) {override fun success (data: FilterEntity) {/ / processing data}})
When the user chooses to filter the data, it needs to be uploaded to the server. The pseudo code is as follows:
/ / upload the json example as follows: [0Power1, jsonData 2] val filterList = ArrayList () / / add int data filterList.add (321) filterList.add (671) val jsonData = JsonUtil.toJson (filterList) / / upload server HttpTool.put (FILTER_DATA) .param ("data", jsonData) / / Gson conversion method fun toJson (object: Any): String {var str = "try {str = gson.toJson (object)} catch (e: Exception) {} return str}
What's more, if you want to upload data of multiple data types, such as key-value, to the server, the pseudo code is as follows:
/ / json data example: {"group": [222,23,24], "brand": [1mem2 3Query 4]} / customer grouping filtering val customerGroupJsonArray = ArrayList () val map = ArrayMap () customerGroupList.forEach {customerGroupJsonArray.add (it.id)} map ["group"] = customerGroupJsonArray / / Brand filtering val vehicleBrandJsonArray = ArrayList () vehicleBrandList.forEach {vehicleBrandJsonArray.add (it.brandId)} map ["brand"] = vehicleBrandJsonArray / / convert map type data val jsonData = JsonUtil.toJson (map) / / upload server HttpTool.put (FILTER_DATA) .param ("data", jsonData)
6. Summary
This paper summarizes the interaction mode and data type between Android and the server, and summarizes the simple application of the data format in the actual project, the application scenario of the data format is far more than the above-mentioned scenarios, and will continue to improve in the later stage. If there are any deficiencies, welcome to point out.
After reading the above, do you have any further understanding of the password of data exchange between the Android client and the server? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.