Refer to: http://osamashabrez.com/client-server-communication-android-json/

This is a sequel to my last blog post about Client Server Communication In Android in which I discussed how to implement client server communication with default HTTPClient with GET and POST request. In this tutorial we’ll be covering the next part doing communication with the server through JSON.



Based on JavaScript object literals JSON is a textual representation of complex data instances. It has 4 basic types:

  • Strings
  • Numbers
  • Boolean
  • Null

Out of these four types objects or arrays can be constructed where
object in terms of JSON is used for key-value pairs. The entire
specification can be read at RFC 4627
just in case. If you are new to this name and never heard of JSON class
before or don’t want to go over all the PFC details, here are a few
JSON examples that will help you clear you mind about how this works.

JSON Numbers: 47, 2.5e15, 0, -7.2e8. These are all JSON numbers whereas 0005 or 02 are not, as there must be no leading zero.

JSON Strings:
JSON Strings are declared with double quotes (“This is a JSON String”)
and string literals with single quotes are an error. JSON also supports
hexa digits with strings.

JSON Literals: Literals are true, false and null.

JSON Array: Array in JSON can be declared via square parenthesis.

["hello, this is my", 2, "tut on android", true]
1
["hello, this is my", 2, "tut on android", true]

Two declare array inside an array as an element we’ll write as:

[["hello", "this", "is", "my"], 2, ["tut", "on", "android"], true]
1
[["hello", "this", "is", "my"], 2, ["tut", "on", "android"], true]

JSON Objects: Objects or key-value pairs are declared with curly brackets as:

{"A": "first object", "B": 2, "C": "third object"}
1
{"A": "first object", "B": 2, "C": "third object"}

And just as we declared arrays inside another array we can declare objects inside an object.

{"A": {1:"A1", 2:"B1"}, "B" :{ "abc":123, "xyz":789}, "C": "finish"}
1
{"A": {1:"A1", 2:"B1"}, "B" :{ "abc":123, "xyz":789}, "C": "finish"}

or

{
"A":{
1:"A1",
2:"B1"
},
"B" :{
"abc":123,
"xyz":789
},
"C": "finish"
}
1
2
3
4
5
6
7
8
9
10
11
{
"A":{
      1:"A1",
      2:"B1"
},
"B" :{
      "abc":123,
      "xyz":789
},
"C": "finish"
}

Why JSON over XML

JSON is more appropriate to use specially in case of mobile communication because it’s not cluttered with the “Well Designed XML Tag Names” and hence is not less bandwidth consuming yet very powerful. So using JSON objects to communicate with your server will be more appropriate then transmitting a XML file and then getting back a XML result.

Before we begin with the code, you can download the source from:

So lets begin with the project explanation:

Build JSON Object

JSONObject jsonobj; // declared locally so that it destroys after serving its purpose
jsonobj = new JSONObject();
try {
// adding some keys
jsonobj.put("key", "value");
jsonobj.put("weburl", "hashincludetechnology.com");

// lets add some headers (nested JSON object)
JSONObject header = new JSONObject();
header.put("devicemodel", android.os.Build.MODEL); // Device model
header.put("deviceVersion", android.os.Build.VERSION.RELEASE); // Device OS version
header.put("language", Locale.getDefault().getISO3Language()); // Language
jsonobj.put("header", header);
// Display the contents of the JSON objects
buildref.setText(jsonobj.toString(2));
} catch (JSONException ex) {
buildref.setText("Error Occurred while building JSON");
ex.printStackTrace();
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
JSONObject jsonobj; // declared locally so that it destroys after serving its purpose
jsonobj = new JSONObject();
try {
    // adding some keys
    jsonobj.put("key", "value");
    jsonobj.put("weburl", "hashincludetechnology.com");
 
    // lets add some headers (nested JSON object)
    JSONObject header = new JSONObject();
    header.put("devicemodel", android.os.Build.MODEL); // Device model
    header.put("deviceVersion", android.os.Build.VERSION.RELEASE); // Device OS version
    header.put("language", Locale.getDefault().getISO3Language()); // Language
    jsonobj.put("header", header);
    // Display the contents of the JSON objects
    buildref.setText(jsonobj.toString(2));
} catch (JSONException ex) {
    buildref.setText("Error Occurred while building JSON");
    ex.printStackTrace();
}

So here we declared a JSON object jsonobj, added some key-value pairs in it named key and weburl. Values of those keys were value and hashincludetechnology.com. Next to demonstrate the nesting JSON Objects, another JSON object headers and added some information about the device test will be tested from including device model, device version and language in ISO3.

If you haven’t downloaded the source you need not to worry the buildref is nothing except a reference to the EditText box on screen.

Send JSON To The Server

In the next part we’ll send our object over the network to our server side script to make things clear I’ll break the code into smaller chunks.

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppostreq = new HttpPost(wurl);
StringEntity se = new StringEntity(jsonobj.toString());
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
httppostreq.setEntity(se);
HttpResponse httpresponse = httpclient.execute(httppostreq);
1
2
3
4
5
6
7
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppostreq = new HttpPost(wurl);
StringEntity se = new StringEntity(jsonobj.toString());
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
httppostreq.setEntity(se);
HttpResponse httpresponse = httpclient.execute(httppostreq);

Here we declared a httpclient and httppostreq object pretty same as we did in our last tutorial and then inside a StringEntity we decoded our JSON object into string. With adding a few required headers to mimic the POST behavior we are now ready to send our JSON object over the network by adding this StringEntity into our POST Req object and getting a response from the server.

HttpEntity resultentity = httpresponse.getEntity();
InputStream inputstream = resultentity.getContent();
Header contentencoding = httpresponse.getFirstHeader("Content-Encoding");
if(contentencoding != null && contentencoding.getValue().equalsIgnoreCase("gzip")) {
inputstream = new GZIPInputStream(inputstream);
}
String resultstring = convertStreamToString(inputstream);
inputstream.close();
resultstring = resultstring.substring(1,resultstring.length()-1);
recvdref.setText(resultstring + "\n\n" + httppostreq.toString().getBytes());
JSONObject recvdjson = new JSONObject(resultstring);
recvdref.setText(recvdjson.toString(2));
1
2
3
4
5
6
7
8
9
10
11
12
HttpEntity resultentity = httpresponse.getEntity();
InputStream inputstream = resultentity.getContent();
Header contentencoding = httpresponse.getFirstHeader("Content-Encoding");
if(contentencoding != null && contentencoding.getValue().equalsIgnoreCase("gzip")) {
    inputstream = new GZIPInputStream(inputstream);
}
String resultstring = convertStreamToString(inputstream);
inputstream.close();
resultstring = resultstring.substring(1,resultstring.length()-1);
recvdref.setText(resultstring + "\n\n" + httppostreq.toString().getBytes());
JSONObject recvdjson = new JSONObject(resultstring);
recvdref.setText(recvdjson.toString(2));

Here we received a reply from the server back and displayed the returned data into another on screen EditText field. If you take a closer look you’ll see that we are extracting contents from a gzip, this is so if your server has gzip enabled then the application will extract the contents and will save them back to the same InputStream object. I have removed some basic error checks in this code snippet please refer to the project source to stay with the best practices.

Something missing, isn’t it? the convertStreamToString() function?

private String convertStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (Exception e) {
Toast.makeText(this, "Stream Exception", Toast.LENGTH_SHORT).show();
}
return total.toString();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
private String convertStreamToString(InputStream is) {
    String line = "";
    StringBuilder total = new StringBuilder();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    try {
        while ((line = rd.readLine()) != null) {
            total.append(line);
        }
    } catch (Exception e) {
    Toast.makeText(this, "Stream Exception", Toast.LENGTH_SHORT).show();
    }
return total.toString();
}

This code was tested on Samsung GT-i9100 with wamp server (v2.1, apache 2.2.1.7 and php 5.3.4) on my local machine.

Application screenshots

Internet Permissions

To get access to internet at Android, following field must be included to AndroidManifest.xml file of the project:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Hope this tutorial will server your purpose of understanding the basics of JSON Object transfers. In case of any difficulties, queries or questions you can post a comment and I’ll get back to you as early as possible. The code might be mess as I was doing a project along (will be releasing my first app soon) and keep going back and forth, bare with that and happy coding!

Android: Client-Server communication by JSON的更多相关文章

  1. AndroidAsync :异步Socket,http(client+server),websocket和socket.io的Android类库

    AndroidAsync是一个用于Android应用的异步Socket,http(client+server),websocket和socket.io的类库.基于NIO,没有线程.它使用java.ni ...

  2. 【Android】与服务器实现JSON数据通信

    一.前言 作为一名移动端开发人员,具备一定的服务端开发能力也是非常必要的,本篇博客讲述如何在Android和服务器之间实现JSON数据通信交互,博客内容基于另外一篇博客:[Web]Eclipse + ...

  3. Android Netty Server

    项目源码在github上,请看这里-->Android Netty Server Android netty server Start a netty server on android Dow ...

  4. iOS解析Server端返回JSON数据

    在做quhao APP架构时,后台Server端使用了Java,提供WebService,而iOS和Android作为移动客户端.在做数据交互时,Server端返回JSON格式数据.由于iOS SDK ...

  5. Client–server model

    Client–server model From Wikipedia, the free encyclopedia The client–server model of computing ] Oft ...

  6. 1. Retrofit2 -- Getting Started and Create an Android Client

    1. Retrofit2 -- Getting Started and Create an Android Client Retrofit tutorial 什么是 Retrofit 如何申明请求 准 ...

  7. Android okHttp网络请求之Json解析

    前言: 前面两篇文章介绍了基于okHttp的post.get请求,以及文件的上传下载,今天主要介绍一下如何和Json解析一起使用?如何才能提高开发效率? okHttp相关文章地址: Android o ...

  8. 深入浅出 Redis client/server交互流程

    综述 最近笔者阅读并研究redis源码,在redis客户端与服务器端交互这个内容点上,需要参考网上一些文章,但是遗憾的是发现大部分文章都断断续续的非系统性的,不能给读者此交互流程的整体把握.所以这里我 ...

  9. Android中使用Gson解析JSON数据的两种方法

    Json是一种类似于XML的通用数据交换格式,具有比XML更高的传输效率;本文将介绍两种方法解析JSON数据,需要的朋友可以参考下   Json是一种类似于XML的通用数据交换格式,具有比XML更高的 ...

随机推荐

  1. [loj6088]可持久化最长不降子序列

    考虑二分求LIS的过程,就是维护一个序列,其中第i个数表示长度为i的最小结尾,而插入操作就是查找第一个大于x的位置并替换掉 用线段树维护,二分的过程也可以用线段树来完成,对线段树可持久化即可 1 #i ...

  2. form-create 3.0 版本发布,好用的Vue3版本动态表单生成组件

    form-create 是一个可以通过 JSON 生成具有动态渲染.数据收集.验证和提交功能的表单生成组件.支持2个UI框架,并且支持生成任何 Vue 组件.内置20种常用表单组件和自定义组件,再复杂 ...

  3. 基于Docker搭建Maven私服Nexus,Nexus详解

    备注:首先在linux环境安装Java环境和Docker,私服需要的服务器性能和硬盘存储要高一点,内存不足可能到时启动失败,这里以4核8GLinux服务器做演示 一:基于Docker安装nexus3 ...

  4. [洛谷P2000 拯救世界]

    生成函数版题. 考虑对于这些条件写出\(OGF\) \(1 + x^6 + x^{12} + x^{18}..... = \frac{1}{1 - x^6}\) \(1 + x + x ^ 2 + x ...

  5. 洛谷 P4240 - 毒瘤之神的考验(数论+复杂度平衡)

    洛谷题面传送门 先扯些别的. 2021 年 7 月的某一天,我和 ycx 对话: tzc:你做过哪些名字里带"毒瘤"的题目,我做过一道名副其实的毒瘤题就叫毒瘤,是个虚树+dp yc ...

  6. 使用BRAKER2进行基因组注释

    来自:https://www.jianshu.com/p/e6a5e1f85dda 使用BRAKER2进行基因组注释 BRAKER2是一个基因组注释流程,能够组合GeneMark,AUGUSTUS和转 ...

  7. 25-ZigZag Conversion

    The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...

  8. LeetCode一维数组的动态和

    一维数组的动态和 题目描述 给你一个数组 nums.数组「动态和」的计算公式为:runningSum[i] = sum(nums[0]...nums[i]). 请返回 nums 的动态和. 示例 1: ...

  9. 零基础学习java------26--------获取省访问量的top3,APP版本数据分析,事务,json,json字符串与对象间的相互转换,求电影平均分

    一. day23中的ip,url案例(前面答案错了) 思路分析: 1.创建javabean,用来存储ip.txt各字段的信息 2. 创建java工具类,封装相应的方法 (1) 加载读取ip.txt文档 ...

  10. CSS系列,三栏布局的四种方法

    三栏布局.两栏布局都是我们在平时项目里经常使用的,今天我们来玩一下三栏布局的四种写法,以及它的使用场景. 所谓三栏布局就是指页面分为左中右三部分然后对中间一部分做自适应的一种布局方式. 1.绝对定位法 ...