Android + PHP 连接

Android + PHP connection

我的主机帐户中有一个 php 文件 url link 是 --http://www.example.com/hello.php 我在文件 hello.php 中有简单的行代码。 当在 Android 中按下按钮时,我试图从 php 文件中获取文本 "Hello" 并将其显示在 textView 中。 可以吗?如果给我一些 examples.Since 我还没有开发任何基于网络连接的 android 应用程序,我不知道这是怎么回事。

这样做应该非常简单:

 URL url = new URL("http://www.android.com/");
 HttpURLConnection urlConnection = (HttpURLConnection)   url.openConnection();
 try {
    InputStream in = new   BufferedInputStream(urlConnection.getInputStream());
    readStream(in);
 finally {
    urlConnection.disconnect();
 }
}

您可以 return 一个 JSON 字符串或您在 PHP 代码中需要的任何内容。

您可以在 android here 中了解有关建立 HTTP 连接的更多信息,并始终记得在后台执行此操作以避免 NetworkOnMainThread 异常。

以下代码适用于 GET 和 POST。

import android.app.Activity;
        import android.app.ProgressDialog;
        import android.content.Context;
        import android.os.AsyncTask;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.TextView;
        import java.io.BufferedReader;
        import java.io.DataOutputStream;
        import java.io.IOException;
        import java.io.InputStreamReader;
        import java.net.HttpURLConnection;
        import java.net.MalformedURLException;
        import java.net.URL;
        import java.net.URLEncoder;


        public class MainActivity extends Activity {

            private ProgressDialog progress;

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

            }


    //calling POST request
            public void sendPostRequest(View View) {
                new PostClass(this).execute();
            }

            public void sendGetRequest(View View) {
                new GetClass(this).execute();
            }

            private class PostClass extends AsyncTask<String, Void, Void> {

                private final Context context;

                public PostClass(Context c){

                    this.context = c;
        //            this.error = status;
        //            this.type = t;
                }

                protected void onPreExecute(){
                    progress= new ProgressDialog(this.context);
                    progress.setMessage("Loading");
                    progress.show();
                }

                @Override
                protected Void doInBackground(String... params) {
                    try {

                        final TextView outputView = (TextView) findViewById(R.id.showOutput);
    //your url goes here
                        URL url = new URL("http://www.example.com/hello.php");

                        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
// parameters to the url if required
                        String urlParameters =
                                "key=" + URLEncoder.encode("a12345", "UTF-8") +
                                        "&username=" + URLEncoder.encode("example@gmail.com", "UTF-8")+
                                        "&password=" +URLEncoder.encode("123456", "UTF-8")+
                                        "&device_id=" +URLEncoder.encode("1", "UTF-8");
                        connection.setRequestMethod("POST");
                        connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
                        connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
                        connection.setDoOutput(true);
                        DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
                        dStream.writeBytes(urlParameters);
                        dStream.flush();
                        dStream.close();
                        int responseCode = connection.getResponseCode();

                        System.out.println("\nSending 'POST' request to URL : " + url);
                        System.out.println("Post parameters : " + urlParameters);
                        System.out.println("Response Code : " + responseCode);
        //get our response here
                        final StringBuilder output = new StringBuilder("Request URL " + url);
                        output.append(System.getProperty("line.separator") + "Request Parameters " + urlParameters);
                        output.append(System.getProperty("line.separator")  + "Response Code " + responseCode);
                        output.append(System.getProperty("line.separator")  + "Type " + "POST");
                        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        String line = "";
                        StringBuilder responseOutput = new StringBuilder();
                        System.out.println("output===============" + br);
                        while((line = br.readLine()) != null ) {
                            responseOutput.append(line);
                        }
                        br.close();

                        output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());

                        MainActivity.this.runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                outputView.setText(output);
                                progress.dismiss();
                            }
                        });


                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    return null;
                }

                protected void onPostExecute() {
                    progress.dismiss();
                }

            }

            private class GetClass extends AsyncTask<String, Void, Void> {

                private final Context context;

                public GetClass(Context c){
                    this.context = c;
                }

                protected void onPreExecute(){
                    progress= new ProgressDialog(this.context);
                    progress.setMessage("Loading");
                    progress.show();
                }

                @Override
                protected Void doInBackground(String... params) {
                    try {

                        final TextView outputView = (TextView) findViewById(R.id.showOutput);
                        URL url = new URL("http://requestb.in/1cs29cy1");

                        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                        String urlParameters = "fizz=buzz";
                        connection.setRequestMethod("GET");
                        connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
                        connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");

                        int responseCode = connection.getResponseCode();

                        System.out.println("\nSending 'POST' request to URL : " + url);
                        System.out.println("Post parameters : " + urlParameters);
                        System.out.println("Response Code : " + responseCode);

                        final StringBuilder output = new StringBuilder("Request URL " + url);
                        //output.append(System.getProperty("line.separator") + "Request Parameters " + urlParameters);
                        output.append(System.getProperty("line.separator")  + "Response Code " + responseCode);
                        output.append(System.getProperty("line.separator")  + "Type " + "GET");
                        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        String line = "";
                        StringBuilder responseOutput = new StringBuilder();
                        System.out.println("output===============" + br);
                        while((line = br.readLine()) != null ) {
                            responseOutput.append(line);
                        }
                        br.close();

                        output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());

                        MainActivity.this.runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                outputView.setText(output);
                                progress.dismiss();

                            }
                        });


                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    return null;
                }

        //        protected void onPostExecute() {
        //            progress.dismiss();
        //        }

            }


        }