2014-07-23 83 views
0

我創建了一個活動來測試從我的應用程序連接到WAMP服務器。但目前它似乎沒有工作。從android應用程序連接到服務器的問題?

活動應該在連接到服務器並單擊按鈕後更改屏幕上的文本框。但目前它不會改變。

下面的代碼有錯誤嗎?注意:我在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 ""; 
    } 

?> 
+0

爲什麼不嘗試使用調試器或僅使用'Log.d(..)'進行調試?檢查是否到達AsyncTask'doInBackground',然後檢查結果是否返回到'onPostExecute'。在'executeHttpRequest'中檢查服務器的確切響應。另外,請檢查IP是否正確,並且您的設備已連接到正確的無線網絡。對於模擬器,你可以嘗試'localhost',雖然沒有保證。 – Marius

+0

您是否嘗試將您的網址粘貼到瀏覽器中以測試連接? – scrayne

+0

是的,我能夠使用PHP腳本填充MySQL數據庫,但我似乎無法獲得與Android應用程序的任何連接!? – rossjAva2015

回答

0

你有行

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

在您的清單文件?

+0

是的,我願意。我不確定這個問題會非常令人生氣! – rossjAva2015

相關問題