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

I was working of an android project recently and now I guess .. I am done with my part. Yeah its a team of 4 and the project was divided accordingly. One of the responsibilities I was assigned was the development of Online Leader Board. While I was working, I searched through Internet and found a few examples as well, – I wonder which question Google couldn’t answer?

All of them were either to much complicatedly explained or didn’t cover the complete concepts behind a complete Client Server Communication In Android. Either the writers were assuming that the person who’ll land of this page will be intelligent enough to guess the other part or were simple not interested of posting a complete solution to someone’s problem. And for the same reason I am writing this post, so if someone else lands on this page while searching the same problem he/she could find a complete solution to their needs.

In this tutorial I’ll be assuming that you at least:

  • Have a basic knowledge of android
  • Have already developed a few small android application (e.g calculators, alarm, reminder etc.)

If you are new to android development, please leave me a comment and I might start from the beginning.

The Real Post Starts From Here:

In spite of using the 3rd party API’s, json classes etc. I’ll be using the default HttpClient from org.apache.http package. For those who want to get the code snippet just and not want me to explain it, the code will be as follows:

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://example.com/script.php?var1=androidprogramming");
try {
HttpResponse response = httpclient.execute(httpget);
if(response != null) {
String line = "";
InputStream inputstream = response.getEntity().getContent();
line = convertStreamToString(inputstream);
Toast.makeText(this, line, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Unable to complete your request", Toast.LENGTH_LONG).show();
}
} catch (ClientProtocolException e) {
Toast.makeText(this, "Caught ClientProtocolException", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, "Caught IOException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "Caught Exception", Toast.LENGTH_SHORT).show();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://example.com/script.php?var1=androidprogramming");
try {
    HttpResponse response = httpclient.execute(httpget);
    if(response != null) {
        String line = "";
        InputStream inputstream = response.getEntity().getContent();
        line = convertStreamToString(inputstream);
        Toast.makeText(this, line, Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(this, "Unable to complete your request", Toast.LENGTH_LONG).show();
    }
} catch (ClientProtocolException e) {
    Toast.makeText(this, "Caught ClientProtocolException", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
    Toast.makeText(this, "Caught IOException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
    Toast.makeText(this, "Caught Exception", Toast.LENGTH_SHORT).show();
}
  • GET is used to know how actually the code is working.
  • Default strings from android strings.xml are not used to avoid useless explanation for this tutorial but they are the recommended way too use while designing an app rather then hard coded strings.

Client server communication is this much simple when it comes to android.

  • Create HttpClient with the default constructor.
  • Create a HttpGet or HttpPost object depending upon your needs, in this case I made a GET object so that we can know whats going on.
  • Initialize the object with a GET or POST url.
  • Execute the GET/POST object through the Http and you’ll get the server’s response in the response object of HttpResponse.

Fetching Data From HttpResponse:

Now the next part is how to fetch data received from the server in HttpResponse object. The server response can be type casted into InputStream object which will then parse the response into simple String. here is the code to do that:

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();
}

So now the code is completed for the client side and we will be focusing on the server side script. The example above will show a notification of the string response the server will send back, here is the code snippet I wrote in php for the server side.

$connection = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die('Unable to connect');
$db = mysql_selectdb(DB_NAME,$connection) or die('Database not found');
if(isset($_GET['var'])) :
$query = "SELECT [a few parameters] FROM [some table] WHERE [some conditions]";
$resultset = mysql_query($query);
$row = mysql_fetch_array($resultset)
echo $row['[column name]'];
else:
echo "No get Request Received";
endif;
1
2
3
4
5
6
7
8
9
10
$connection = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die('Unable to connect');
$db = mysql_selectdb(DB_NAME,$connection) or die('Database not found');
if(isset($_GET['var'])) :
    $query = "SELECT [a few parameters] FROM [some table] WHERE [some conditions]";
    $resultset = mysql_query($query);
    $row = mysql_fetch_array($resultset)
    echo $row['[column name]'];
else:
    echo "No get Request Received";
endif;

Warning:

  • Implement proper checks for data filtration. The code above was meant for the tutorial and is not enough to use in a market application.

This completes this small tutorial here, now a few of the most asked questions while doing the client server communication:

  1. Why not use the XML approach while performing the client server data transfer operations:

    This was my first android application which used internet permissions
    and fetched data on runtime from server, I found it more interesting to
    work first manually with writing my own script and then go for the
    proper XML approach.
  2. Why not use the JSON library for client server application in fact of using an array for GET or POST request:

    Answer remains the same for this question as well. I have implemented my
    own methods and know how HTTP works in android. Next I’ll be using JSON
    and then switch to XML, JSON tutorial will be the next one in this
    series.
  3. Some other questions:

    Post them into the comments section and I’ll be happy to answer them
    right away. If you are enough experienced and found this approach not
    practicable while developing apps for the market, please provide your
    valuable feedback in that case as well. We warmly welcome a healthy and
    fruitful discussion here.

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>
1
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

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

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

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

  2. Android Netty Server

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

  3. Client–server model

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

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

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

  5. Network client/server

    <Beginning Linux Programming_4th>  chapter 15 Sockets 1  A simple local client/server 1)  clie ...

  6. Linux SocketCan client server demo hacking

    /*********************************************************************** * Linux SocketCan client se ...

  7. NetMQ(ZeroMQ)Client => Server => Client 模式的实现

    ØMQ (也拼写作ZeroMQ,0MQ或ZMQ)是一个为可伸缩的分布式或并发应用程序设计的高性能异步消息库.它提供一个消息队列, 但是与面向消息的中间件不同,ZeroMQ的运行不需要专门的消息代理(m ...

  8. Android Http Server

    Android Http Server 1 引言          Android如何构建Http服务器呢?本文的小例子,约莫着,还是能做个参考的^^.恩,例子实现的是PC浏览手机文件,支持了下载和删 ...

  9. 【转】Android Web Server

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://vaero.blog.51cto.com/4350852/1188602 Andr ...

  10. 【转】Android Http Server

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://vaero.blog.51cto.com/4350852/939413 Andro ...

随机推荐

  1. 如何看待 SAE 在2014 年 3 月 24 日发生的的大面积宕机事故?

    3 月 24 日晚间大约 23 点左右,新浪云 SAE 一处核心机柜掉电,导致 SAE 平台下大量应用无法正常访问,并在 10 小时后才陆续修复.这次事故暴露 SAE 的哪些缺陷?SAE 运维人员又是 ...

  2. [atARC115D]Odd Degree

    考虑对于一棵树$G$,这个问题的答案-- 当$k$为奇数时答案显然为0,否则从$V$中任选$k$个点,以任意一点为根,从底往上不难发现子图数量唯一 换言之,当$k$为偶数时,每一个合法(恰有$k$个奇 ...

  3. [atARC101F]Robots and Exits

    每一个点一定匹配其左边/右边的第一个出口(在最左/右边的出口左/右边的点直接删除即可),否则记到左右出口的距离分别为$x_{i}$和$y_{i}$ 令$p_{i}$表示$i$匹配的出口(左0右1),结 ...

  4. [bzoj1032]祖码

    先将连续的一段相同的点连起来,然后考虑对于一段区间,分两种情况:1.首尾两点再同时消掉,必然要先将去掉首尾的一段消掉后再消2.首尾两点再不同时刻消掉,那么必然存在一个断点k,使得k左右无关(题目中的错 ...

  5. 微信小程序如何重写Page方法?以及重写Page方法给开发者带来的好处

    17,18年的时候,我当时主要开发小程序,那时候领导想看一下小程序的访问量,还有一些埋点的需求,于是我们的小程序就接入了阿拉丁统计. 阿拉丁的接入方式除了配置以外,主要就一行引入代码.官方要求将以下代 ...

  6. 用图像识别玩Chrome断网小游戏

    先来看一下效果 正文 最近在学习机器学习方面的知识,想着做个东西玩玩,然后就接触到了TensorFlow这个机器学习框架,这个框架封装了机器学习的一些常用算法. 不过要自己实现一套流程还是比较麻烦,我 ...

  7. c语言printf输出最前端字符不显示

    原因:语法错误,和其它语言语法混用. printf("链表长度 : %d \n",length); printf("length is : %d \n",len ...

  8. Codeforces 1188E - Problem from Red Panda(找性质+组合数学)

    Codeforces 题面传送门 & 洛谷题面传送门 咦,题解搬运人竟是我? 一道很毒的计数题. 先转化下题意,每一次操作我们可以视作选择一种颜色并将其出现次数 \(+k\),之后将所有颜色的 ...

  9. Atcoder Grand Contest 020 E - Encoding Subsets(记忆化搜索+复杂度分析)

    Atcoder 题面传送门 & 洛谷题面传送门 首先先考虑如果没有什么子集的限制怎样计算方案数.明显就是一个区间 \(dp\),这个恰好一年前就做过类似的题目了.我们设 \(f_{l,r}\) ...

  10. 《python编程从入门到实践》读书实践笔记(二)

    本文是<python编程从入门到实践>读书实践笔记11章的内容,主要包含测试,为体现测试的重要性,独立成文. 11 测试代码 写在前面的话,以下是我这些年开发中和测试相关的血泪史. 对于一 ...