nainai1 发表于 2017-4-2 14:45:26

Android访问php取回json数据

Android访问php取回json数据
  

  转载:http://www.oschina.net/code/snippet_12_1122


1$array = array(
2'username'=>'杨铸',
3'password'=>'123456',
4'user_id'=>1
5);
6echo json_encode($array);



2.[代码]java代码
01private voidstartUrlCheck(String username,String password)
02{
03HttpClient client =new DefaultHttpClient();
04StringBuilder builder =new StringBuilder();
05
06HttpGet myget =new HttpGet("http://10.0.2.2/Android/index.php");
07try{
08HttpResponse response = client.execute(myget);
09BufferedReader reader =new BufferedReader(newInputStreamReader(
10response.getEntity().getContent()));
11for(String s = reader.readLine(); s != null; s = reader.readLine()) {
12builder.append(s);
13}
14JSONObject jsonObject =new JSONObject(builder.toString());
15String re_username = jsonObject.getString("username");
16String re_password = jsonObject.getString("password");
17intre_user_id = jsonObject.getInt("user_id");
18setTitle("用户id_"+re_user_id);
19Log.v("url response","true="+re_username);
20Log.v("url response","true="+re_password);
21} catch (Exception e) {
22Log.v("url response","false");
23e.printStackTrace();
24}
25}



3.[代码]运行说明
01其中http://10.0.2.2为Android访问本机url的ip地址。对应电脑上测试的http://127.0.0.1
02
03另外执行代码时会抛出异常
04
05java.net.SocketException: Permission denied
06
07此为应用访问网络的权限不足 在AndroidManifest.xml中,需要进行如下配置:
08<uses-permission Android:name="android.permission.INTERNET" />
09就加在
10</manifest>
11之前就好了
12然后测试通过。
页: [1]
查看完整版本: Android访问php取回json数据