问题从Android应用程序连接到服务器?

时间:2014-07-23 13:50:26

标签: php android wamp

我创建了一个活动来测试从我的App到WAMP服务器的连接。但是目前它似乎没有用。

一旦连接到服务器并单击按钮,活动就应该更改屏幕上的文本框。但是目前它并没有改变。

以下代码是否有错误?注意:我在Logcat中看不到任何错误,并且服务器日志没有显示连接。

服务器类:

 public class Server {

        // Declared Constants
        public static final String SERVER_URL = "http://192.168.56.1/androidtest.php"; //need to change?

        /**
         * Gets the bit of text to set
         * @return A string containing the text to set
         */
        public static String getTextToSet() {
                /*
                 * Let's construct the query string. It should be a key/value pair. In
                 * this case, we just need to specify the command, so no additional
                 * arguments are needed.
                 */
                String data = "command=" + URLEncoder.encode("getTextToSet");
                return executeHttpRequest(data);
        }

        /**
         * Helper function used to communicate with the server by sending/receiving
         * POST commands.
         * @param data String representing the command and (possibly) arguments.
         * @return String response from the server.
         */
        private static String executeHttpRequest(String data) {
                String result = "";
                try {
                        URL url = new URL(SERVER_URL);
                        URLConnection connection = url.openConnection();


                        /*
                         * We need to make sure we specify that we want to provide input and
                         * get output from this connection. We also want to disable caching,
                         * so that we get the most up-to-date result. And, we need to 
                         * specify the correct content type for our data.
                         */
                        connection.setDoInput(true);
                        connection.setDoOutput(true);
                        connection.setUseCaches(false);
                        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                        //connection.setRequestProperty("Content -Type", "textback.php");
                        //connection.setRequestProperty("Value1", "Value2");

                        // Send the POST data
                        DataOutputStream dataOut = new DataOutputStream(connection.getOutputStream());
                        dataOut.writeBytes(data);
                        dataOut.flush();
                        dataOut.close();

                        // get the response from the server and store it in result
                        DataInputStream dataIn = new DataInputStream(connection.getInputStream()); 
                        String inputLine;
                        while ((inputLine = dataIn.readLine()) != null) {
                                result += inputLine;
                        }
                        dataIn.close();
                } catch (IOException e) {
                        /*
                         * In case of an error, we're going to return a null String. This
                         * can be changed to a specific error message format if the client
                         * wants to do some error handling. For our simple app, we're just
                         * going to use the null to communicate a general error in
                         * retrieving the data.
                         */
                        e.printStackTrace();
                        result = null;
                }

                return result;
        }
    }

连接到服务器类:

public class ConnectToServer extends Activity {

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

        final String textToSetAs = null;
        TextView tv = (TextView) findViewById(R.id.text_to_set);

        // Call the task to set the text on screen
        Button setText = (Button) findViewById(R.id.button_to_set_text);
        setText.setOnClickListener(new OnClickListener()

        {
            @Override
            public void onClick(View v) {

                (new GetTextTask()).execute();

            }
        });
    }

    /**
//   * Used to spawn a thread to retrieve the animal sound?
     */
    @SuppressWarnings("unchecked")
    private class GetTextTask extends AsyncTask {

        /**
         * Let's make the http request and return the result as a String.
         */
        protected String doInBackground(Object... args) {

            // Return the server call to get the text to set
            return Server.getTextToSet();

        }

        /**
         * Display the result as a Toast.
         */
        protected void onPostExecute(Object objResult) {
            // check to make sure we're dealing with a string
            /*
             * if (objResult != null && objResult instanceof String) { String
             * result = (String) objResult;
             * Toast.makeText(getApplicationContext(), result,
             * Toast.LENGTH_SHORT).show(); }
             */

            TextView tv = (TextView) findViewById(R.id.text_to_set);
            tv.setText((CharSequence) objResult);
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

PHP脚本:

<?php

  echo "Did it work?";
  // get the command
  $command = $_REQUEST['command'];

  // determine which command will be run
  if($command == "getTextToSet") {
    // return the text to set
    echo "This is what you wanted back?";
  } else {
        echo "";
  }

?>

1 个答案:

答案 0 :(得分:0)

你有线

 uses-permission android:name="android.permission.INTERNET"

在您的清单文件中?

相关问题