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>

最新文章

  1. jQuery-1.9.1源码分析系列(十) 事件系统——事件包装
  2. eclipse配置tomcat 和JRE环境
  3. Ubuntu16.04安装Samba
  4. 太阳系Demo(openGL)
  5. Android关联源码support-v4的问题解决
  6. 完整cocos2d-x编译Andriod应用过程
  7. WPF WebBroswer可以用到的接口
  8. yii2 改变首页,变成登录页
  9. 关于Trie KMP AC自动机
  10. python_Tornado_web_框架_分页
  11. postman简单教程,使用tests模块来验证接口时是否通过
  12. git 强制覆盖分支
  13. python添加post请求
  14. 微信小程序获取手机验证码
  15. Harries-高性能分布式Asp.net通信框架
  16. TimeLine CSS/Javascript 时间线
  17. SQL注入之Sqli-labs系列第十四关(基于双引号POST报错注入)
  18. linux下history命令显示执行时间
  19. Oracle触发器用法实例详解
  20. 使用Akka构建集群(二)

热门文章

  1. Dapr-状态管理
  2. [gym102511K]Traffic Blights
  3. [loj3315]抽卡
  4. Java8-JVM内存区域划分白话解读
  5. myeclipse maven web打包
  6. 【R shiny】一些应用记录
  7. Linux运维工程师面试题整理
  8. “equals”有值 与 “==”存在 “equals”只是比较值是否相同,值传递,==地址传递,null==a,避免引发空指针异常,STRING是一个对象==null,对象不存在,str.equals(&quot;&quot;)对象存在但是包含字符‘&#39;&#39;
  9. 我的分布式微服务框架:YC-Framework
  10. linux下定位异常消耗的线程实战分析