当前位置:Gxlcms > PHP教程 > Android访问php调取json数据

Android访问php调取json数据

时间:2021-07-01 10:21:17 帮助过:21人阅读

做Android项目,离不开去服务器取数据,典型的就是Android访问php调取json数据。网上类似的例子一大堆,而且居然代码都一样,我要吐槽一下,你们发的代码不全,这不是坑人吗。

做这个项目,我们要用到Apache提供的依赖包(jar包):①httpclient ②httpcore ③http-mimi ④apache-mime4j

国际惯例:先上DEMO,下载地址:Android访问php调取json数据

我们先熟悉一下 php下的json数据格式

e.g.

$tnnowu = array(
		'username' => '灬抹茶灬',
		'password' => '666',
		'user_id' => 1
);
echo json_encode($tnnowu);

接着我们编写java代码

MainActivity.java

package com.cnwuth.getjson;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    private void startURLCheck(String username,String password)
    {
        HttpClient httpClient = new DefaultHttpClient();
        StringBuilder stringBuilder = new StringBuilder();

        HttpGet httpGet = new HttpGet("xxx.xxx.php");

        try
        {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
                    httpResponse.getEntity().getContent()
            ));
            for (String s = bufferedReader.readLine();s!=null;s=bufferedReader.readLine())
            {
                stringBuilder.append(s);
            }
            JSONObject jsonObject = new JSONObject(stringBuilder.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();
        }
    }
}

最后,需要网络权限才可以访问数据

AndroidMainifest.xml




    

    
        
            
                

                
            
        
    



关注我的最新动态;新浪微博 @吴天昊TnnoWu

以上就介绍了Android访问php调取json数据,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

人气教程排行