How to retrieve json data by accessing php on Android

Source: Internet
Author: User

1. [Code] php code
1 $ array = array (

2 'username' => 'yangzhu ',

3 'Password' => '123 ',

4 'user _ id' => 1

5 );

6 echo json_encode ($ array );

2. [Code] java code
01 private void startUrlCheck (String username, String password)

02 {

03 HttpClient client = new DefaultHttpClient ();

04 StringBuilder builder = new StringBuilder ();

05

06 HttpGet myget = new HttpGet ("http: // 10.0.2.2/Android/index. php ");

07 try {

08 HttpResponse response = client.exe cute (myget );

09 BufferedReader reader = new BufferedReader (new InputStreamReader (

10 response. getEntity (). getContent ()));

11 for (String s = reader. readLine (); s! = Null; s = reader. readLine ()){

12 builder. append (s );

13}

14 JSONObject jsonObject = new JSONObject (builder. toString ());

15 String re_username = jsonObject. getString ("username ");

16 String re_password = jsonObject. getString ("password ");

17 int re_user_id = jsonObject. getInt ("user_id ");

18 setTitle ("User ID _" + re_user_id );

19 Log. v ("url response", "true =" + re_username );

20 Log. v ("url response", "true =" + re_password );

21} catch (Exception e ){

22 Log. v ("url response", "false ");

23 e. printStackTrace ();

24}

25}

3. [Code] running instructions
01 http: // 10.0.2.2 is the IP address used by Android to access the local url. Http: // 127.0.0.1 tested on the computer

02

03 An exception will be thrown during code execution.

04

05 java.net. SocketException: Permission denied

06

07 in AndroidManifest. xml, the following configuration is required:

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

Add in 09

10 </manifest>

It was good before 11.

12. Then the test passes.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.