Android中获取PHP服务器端Json返回数据注意事项

47 篇文章 0 订阅
29 篇文章 0 订阅

项目中为了节省用户通过3G网络访问系统内容的流量,决定采用Json的方式将服务器数据传递过来。而不是直接使用HTML的方式传输。
测试环境为:
XAMPP中的PHP + MYSQL+ Windows 7+Eclipse+本地网络
Android中的效果图:

在IE中访问地址显示的JSon数据为:

{"title":"TTT","id":1,"value":"TTT"}

java代码:

<?php
     header( "Content-Type: text/html; charset=UTF-8" );
     $type = $_GET [ 'type' ];
     if ( $type == 1)
     {
         //$obj->title = "Test";
         //$obj->id = 1;
         //$obj->value = urlencode("TTT");
         //echo urldecode ( json_encode ($obj));
         $array = array ( 'title' => 'TTT' , 'id' =>1, 'value' =>urlencode( "哈哈" ));
         echo urldecode(json_encode( $array ));
     }
?>

package com.jouhu;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
 
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
 
public class PHPJsonActivity extends Activity {
    /** Called when the activity is first created. */
 
    private String Tag = "PHPJsonActivity";
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //EditText edit = (EditText)findViewById(R.id.editText1);
        //String url = "http://88.88.88.200:8888/phpjson/index.php?type=1";
        //getServerJsonDataWithNoType(url,edit);
        Button btn = (Button)findViewById(R.id.button1);
        btn.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                EditText edit = (EditText)findViewById(R.id.editText1);
                String url = "http://88.88.88.200:8888/phpjson/index.php?type=1";
                getServerJsonDataWithNoType(url,edit);
            }
        });
    }
    public void getServerJsonDataWithNoType(String url,EditText editText)
    {
        int res = 0;
        HttpClient client = new DefaultHttpClient();
        StringBuilder str = new StringBuilder();
        HttpGet httpGet = new HttpGet(url);
        try
        {
            HttpResponse httpRes = client.execute(httpGet);
            httpRes = client.execute(httpGet);
            res = httpRes.getStatusLine().getStatusCode();
            if(res == 200)
            {
                BufferedReader buffer = new BufferedReader(new InputStreamReader(httpRes.getEntity().getContent()));
                for(String s = buffer.readLine(); s != null ; s = buffer.readLine())
                {
                    str.append(s);
                }
                //String out = EntityUtils.toString(httpRes.getEntity().getContent(), "UTF-8");
                //StringBuilder sb = new StringBuilder()
                Log.i(Tag,str.toString());
                try
                {
                    //JSONObject json = new JSONObject(str.toString()).getJSONObject("content");
                    JSONObject json = new JSONObject(str.toString());
                    String title = json.getString("title");
                    Log.i(Tag,title);
                    int id = json.getInt("id");
                    String value = json.getString("value");
                    Log.i(Tag,value);
                    editText.setText("Title:" + title + " ID:" + id + " Value:" + value);
                }
                catch(JSONException e)
                {
                    Log.i(Tag, e.getLocalizedMessage());
                    //buffer.close();
                    e.printStackTrace();
                }
            }
            else
            {
                Log.i(Tag, "HttpGet Error");
            }
        }
        catch(Exception e)
        {
            Log.i(Tag, "Exception");
        }
    }
 
}

1 出现Value of type java.lang.String cannot be converted to JSONObject.这是由于我们的php或者其他服务器脚本有BOM头造成的。可以通过Editplus或者EmEditor或者UltraEditor进行删除。具体可以参考如何用去掉UTF-8的BOM头

编辑器调整为UTF8编码格式后,保存的文件前面会多出一串隐藏的字符(也即是BOM),用于编辑器识别这个文件是否是以UTF8编码。
运行Editplus,点击工具,选择首选项,选中文件,UTF-8标识选择 总是删除签名,
然后对PHP文件编辑和保存后的PHP文件就是不带BOM的了。
ultraedit去除bom头办法
打开文件后,另存为选项的编码格式里选择(utf-8 无bom头),确定就ok了

2 记得在AndroidManifest.XML中加入

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

3 下面应该处理的问题是 中文以及根据数据库中的数据使用ListView或GroupView之类的生成UI。

主参考文章:

http://www.cnblogs.com/tt_mc/archive/2011/01/04/1925327.html

http://www.itxue.com/html/caozuoxitong/WINNT/20101123/7077.html

参考文章:
1 http://www.instropy.com/2010/06/14/reading-a-json-login-response-with-android-sdk/
2 http://www.josecgomez.com/2010/04/30/android-accessing-restfull-web-services-using-json/
3 http://www.cnblogs.com/tt_mc/archive/2011/01/04/1925327.html
4 http://blog.csdn.net/dadoneo/article/details/6233366
5 http://news.cnblogs.com/n/88356/
6 http://blog.lrenwang.com/post/114/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值