Php 从android中的url获取数据

Php 从android中的url获取数据,php,android,json,url,Php,Android,Json,Url,我想从url获取数据。在本例中,我已经获得了完整的php,数据已经转换为json并在localhost中运行(http://localhost/adchara1/index.php/?year=1) 这是php脚本 <?php mysql_connect("localhost","root",""); mysql_select_db("test"); $q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQU

我想从url获取数据。在本例中,我已经获得了完整的php,数据已经转换为json并在localhost中运行(http://localhost/adchara1/index.php/?year=1)

这是php脚本

<?php
 mysql_connect("localhost","root","");
 mysql_select_db("test");
 $q=mysql_query("SELECT * FROM people
 WHERE
 birthyear>'".$_REQUEST['year']."'");
 while($e=mysql_fetch_assoc($q))
         $output[]=$e;
   print(json_encode($output));
   mysql_close(); ?>

我想使用按钮单击并在textview中显示此结果,您只需使用HttpClient执行get请求,并使用JSONArray对象将字符串转换为Json数组


在按钮监听器中编写此代码

        try {
        String url = "http://YourIPAddress/adchara1/index.php/?year=1";
        HttpPost httppost = new HttpPost(url);
        try {
            HttpParams p = new BasicHttpParams();
            HttpClient httpclient = new DefaultHttpClient(p);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclient.execute(httppost,
                    responseHandler);
            JSONArray jArray = new JSONArray(responseBody);
            String text="";
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject e = jArray.getJSONObject(i);
                    text = text + "ID : "+e.getString("id")+"\n";
                    text = text + "Name : "+e.getString("name")+"\n";
                    text = text + "Sex : "+e.getString("sex")+"\n";
                    text = text + "Birthyear : "+e.getString("birthyear")+"\n";
            }
            Textview.setText(text);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    } catch (Throwable t) {
        Toast.makeText(this, "Request failed: " + t.toString(),
                Toast.LENGTH_LONG).show();
        t.printStackTrace();
    }
试试看{
字符串url=”http://YourIPAddress/adchara1/index.php/?year=1";
HttpPost HttpPost=新的HttpPost(url);
试一试{
HttpParams p=新的BasicHttpParams();
HttpClient HttpClient=新的默认HttpClient(p);
ResponseHandler ResponseHandler=新BasicResponseHandler();
字符串responseBody=httpclient.execute(httppost,
负责人);
JSONArray jArray=新的JSONArray(responseBody);
字符串文本=”;
for(int i=0;i
如果您有任何澄清,请通知我

public class main活动扩展活动{
public class MainActivity extends Activity {

AsyncTask<Void, Void, Void> mTask;
String jsonString;

String url = "https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=50cent&count=2";


Button b;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getActionBar().setDisplayHomeAsUpEnabled(true);

    b = (Button) findViewById(R.id.btnFetch);
    final TextView tv = (TextView) findViewById(R.id.txtView);

    mTask = new AsyncTask<Void, Void, Void> () {

        @Override
        protected Void doInBackground(Void... params) {
            try {
                jsonString = getJsonFromServer(url);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            tv.setText(jsonString);

        }

    };

    b.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            mTask.execute();
        }
    });
}


public static String getJsonFromServer(String url) throws IOException {

    BufferedReader inputStream = null;

    URL jsonUrl = new URL(url);
    URLConnection dc = jsonUrl.openConnection();

    dc.setConnectTimeout(5000);
    dc.setReadTimeout(5000);

    inputStream = new BufferedReader(new InputStreamReader(
            dc.getInputStream()));

    // read the JSON results into a string
    String jsonResult = inputStream.readLine();
    return jsonResult;
}

}
异步任务mTask; 字符串jsonString; 字符串url=”https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=50cent&count=2"; 按钮b; @凌驾 创建时的公共void(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getActionBar().setDisplayHomeAsUpEnabled(true); b=(按钮)findViewById(R.id.btnFetch); 最终文本视图tv=(文本视图)findViewById(R.id.txtView); mTask=新的异步任务(){ @凌驾 受保护的Void doInBackground(Void…参数){ 试一试{ jsonString=getJsonFromServer(url); }捕获(IOE异常){ //TODO自动生成的捕捉块 e、 printStackTrace(); } 返回null; } @凌驾 受保护的void onPostExecute(void结果){ super.onPostExecute(结果); tv.setText(jsonString); } }; b、 setOnClickListener(新的OnClickListener(){ 公共void onClick(视图v){ mTask.execute(); } }); } 公共静态字符串getJsonFromServer(字符串url)引发IOException{ BufferedReader inputStream=null; URL jsonUrl=新URL(URL); URLConnection dc=jsonUrl.openConnection(); dc.setConnectTimeout(5000); dc.setReadTimeout(5000); inputStream=新的BufferedReader(新的InputStreamReader( getInputStream()); //将JSON结果读入字符串 字符串jsonResult=inputStream.readLine(); 返回jsonResult; } }
使用此方法从服务器获取jsonString后,可以在Json中解析和显示数据

编辑:出现错误是因为您试图从异步任务中从服务器获取json。您需要在后台执行此操作。您可以使用线程,也可以使用异步任务

Button button =(Button) findViewById(R.id.button);
        TextView tv =(TextView) findViewById(R.id.textview);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String result = connectionFromServer("http://localhost/adchara1/index.php/?year=1");
                tv.setText(result);
            }
        });   

 public static String connectionFromServer(String url) throws IOException {

            BufferedReader inputStream = null;

            URL myurl = new URL(url);
            URLConnection dc = myurl.openConnection();

            dc.setConnectTimeout(5000);
            dc.setReadTimeout(5000);

            inputStream = new BufferedReader(new InputStreamReader(
                    dc.getInputStream()));

            // read the JSON results into a string
            String result = inputStream.readLine();
            return result;
        }

这将在文本视图中显示结果。

我在很多教程中都尝试过这样做,但不起作用,所以我决定提问。你能完成这段代码吗?你到底想问什么?android代码是相同的还是你有任何疑问?在android中,我想从结果中获取url,并在android的textView中显示。例如,在安卓系统中,我有1个按钮和1个文本视图,我想在url
[{“id”:“1”,“name”:“kongkea”,“sex”:“1”,“birthyear”:“1990”},{“id”:“2”,“name”:“thida”,“sex”:“0”,“birthyear”:“2000”}中获得结果,以在文本视图中显示。感谢您的回答,但它不起作用。这是您的代码[谢谢您的回答,但它不起作用。这是您的代码。谢谢。它起作用了。我使用按钮清除文本视图(tv.setText(“”)。然后再次获取数据,但出现错误。y?谢谢您的回答,但它不起作用。谢谢
Button button =(Button) findViewById(R.id.button);
        TextView tv =(TextView) findViewById(R.id.textview);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String result = connectionFromServer("http://localhost/adchara1/index.php/?year=1");
                tv.setText(result);
            }
        });   

 public static String connectionFromServer(String url) throws IOException {

            BufferedReader inputStream = null;

            URL myurl = new URL(url);
            URLConnection dc = myurl.openConnection();

            dc.setConnectTimeout(5000);
            dc.setReadTimeout(5000);

            inputStream = new BufferedReader(new InputStreamReader(
                    dc.getInputStream()));

            // read the JSON results into a string
            String result = inputStream.readLine();
            return result;
        }