Android访问php取回json数据

PHP代码:

$array = array(

array(  'id=>'1',  'text'=>'123'),
array(  'id'=>'2',  'text'=>'456')
)
echo json_encode($array);

Java代码:

private void getJson()
 {
  HttpClient client = new DefaultHttpClient();
  StringBuilder sb = new StringBuilder();
  String mystring="";
  HttpGet myget = new HttpGet("http://yulu520.sinaapp.com/get_list.php?page=1"); //用HttpGet获取网站信息
  try {
   HttpResponse response = client.execute(myget);
   BufferedReader reader = new BufferedReader(new InputStreamReader(
   response.getEntity().getContent()));
   for (String s = reader.readLine(); s != null; s = reader.readLine()) {
    sb.append(s); //读取到sb中
   }
   JSONArray ja=new JSONArray(sb.toString()); //建立JSONArray数组对像
   JSONObject jsonObject=ja.getJSONObject(0); //从JSONArray数组中读取一条json记录
   mystring="第一个Id:"+jsonObject.getInt("id")+"__文本:"+jsonObject.getString("text")+"\n";
   jsonObject=ja.getJSONObject(ja.length()-1);
   mystring+="最后一个Id:"+jsonObject.getInt("id")+"__文本:"+jsonObject.getString("text")+"\n";
   
   tv.setText(mystring);//tv是一个TextView对像
   
  } catch (Exception e) {
   //Log.v("url response", "false");
   tv.setText(e.toString());
  }
 }
 运行说明:

另外执行代码时会抛出异常

java.net.SocketException: Permission denied

此为应用访问网络的权限不足 在AndroidManifest.xml中,需要进行如下配置:
<uses-permission Android:name="android.permission.INTERNET" />
就加在
</manifest>
之前就好了


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值