Android访问php取回json数据实例
程序员文章站
2023-11-25 10:48:34
php代码 复制代码 代码如下: $array = array( 'username'=>'杨铸', 'password'=>'123456', 'user_i...
php代码
$array = array(
'username'=>'杨铸',
'password'=>'123456',
'user_id'=>1
);
echo json_encode($array);
java代码
private void starturlcheck(string username,string password)
{
httpclient client = new defaulthttpclient();
stringbuilder builder = new stringbuilder();
httpget myget = new httpget("http://10.0.2.2/android/index.php");
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()) {
builder.append(s);
}
jsonobject jsonobject = new jsonobject(builder.tostring());
string re_username = jsonobject.getstring("username");
string re_password = jsonobject.getstring("password");
int re_user_id = jsonobject.getint("user_id");
settitle("用户id_"+re_user_id);
log.v("url response", "true="+re_username);
log.v("url response", "true="+re_password);
} catch (exception e) {
log.v("url response", "false");
e.printstacktrace();
}
}
运行说明
其中http://10.0.2.2为android访问本机url的ip地址。对应电脑上测试的http://127.0.0.1
另外执行代码时会抛出异常
java.net.socketexception: permission denied
此为应用访问网络的权限不足 在androidmanifest.xml中,需要进行如下配置:
<uses-permission android:name="android.permission.internet" />
就加在
</manifest>
之前就好了
然后测试通过。
复制代码 代码如下:
$array = array(
'username'=>'杨铸',
'password'=>'123456',
'user_id'=>1
);
echo json_encode($array);
java代码
复制代码 代码如下:
private void starturlcheck(string username,string password)
{
httpclient client = new defaulthttpclient();
stringbuilder builder = new stringbuilder();
httpget myget = new httpget("http://10.0.2.2/android/index.php");
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()) {
builder.append(s);
}
jsonobject jsonobject = new jsonobject(builder.tostring());
string re_username = jsonobject.getstring("username");
string re_password = jsonobject.getstring("password");
int re_user_id = jsonobject.getint("user_id");
settitle("用户id_"+re_user_id);
log.v("url response", "true="+re_username);
log.v("url response", "true="+re_password);
} catch (exception e) {
log.v("url response", "false");
e.printstacktrace();
}
}
运行说明
复制代码 代码如下:
其中http://10.0.2.2为android访问本机url的ip地址。对应电脑上测试的http://127.0.0.1
另外执行代码时会抛出异常
java.net.socketexception: permission denied
此为应用访问网络的权限不足 在androidmanifest.xml中,需要进行如下配置:
<uses-permission android:name="android.permission.internet" />
就加在
</manifest>
之前就好了
然后测试通过。