Android accesses php to retrieve the json data instance
- 2020-05-17 06:21:26
- OfStack
php code
java code
Operating instructions
$array = array(
'username'=>' Yang Zhu ',
'password'=>'123456',
'user_id'=>1
);
echo json_encode($array);
java code
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(" The user 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();
}
}
Operating instructions
Among them http://10.0.2.2 for Android Access to the machine url the ip Address. Corresponding to the computer test http://127.0.0.1
In addition, exceptions are thrown when the code is executed
java.net.SocketException: Permission denied
This is insufficient access to the network for the application in AndroidManifest.xml , the following configuration is required:
<uses-permission Android:name="android.permission.INTERNET" />
Add in
</manifest>
It was done before
Then the test passed.