2013-05-17 39 views
-1

這是我到目前爲止的代碼。通過Android應用程序連接到PHP腳本

public void postData(String toPost) { 
    // Create a new HttpClient and Post Header 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://www.mywebsite.com/dev/reverser.php"); 

    //This is the data to send 
    String MyName = toPost; //any data to send 

    try { 
    // Add your data 
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
    nameValuePairs.add(new BasicNameValuePair("action", MyName)); 

    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

    // Execute HTTP Post Request 

    ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
    String response = httpclient.execute(httppost, responseHandler); 

    //This is the response from a php application 

    String reverseString = response; 
    Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show(); 

    } catch (ClientProtocolException e) { 
    Toast.makeText(this, "CPE response " + e.toString(), Toast.LENGTH_LONG).show(); 
    // TODO Auto-generated catch block 
    } catch (IOException e) { 
    Toast.makeText(this, "IOE response " + e.toString(), Toast.LENGTH_LONG).show(); 
    // TODO Auto-generated catch block 
    } 

    }//end postData() 

有人能告訴我下面的代碼有什麼問題!我已經確定只有try catch塊存在問題,而不是活動中的其他任何地方。我只是不知道它是什麼或如何糾正它。

我的PHP代碼很簡單。這是這樣的 -

//code to reverse the string 
$reversed = strrev($_POST["action"]); 
echo $reversed; 
+0

爲什麼不告訴我們你得到的異常是什麼。您可以使用android調試器來執行此操作。此外,將答覆打印爲吐司的方式也不正確。 – rockstar

+0

AndroidRuntime(15110):java.lang.RuntimeException:無法啓動活動ComponentInfo {com.example.connectingtophpandreturningdata/com.example.connectingtophpandreturningdata.MainActivity}:android.os.NetworkOnMainThreadException –

回答

0

添加爲海報要求這樣做的單獨答案。

假設:

一個)有一個允許的URL的文本框加載

b)中點擊它時,A按鈕上的URL中取出˚F

實現一個按鈕執行聯網操作點擊偵聽器,調用以下函數:

private void URL() 
    { 
     String url = txtURL.getText().toString(); 
     new URLTask().execute(new String[] { url }); 
    }  




private class URLTask extends AsyncTask<String, Void, String> 
    { 
     protected String doInBackground(String... urls) 
     { 

      BufferedReader br = null; 
      String url = urls[0]; 
      StringBuffer sb = new StringBuffer(""); 

      try 
      { 
       HttpClient client = new DefaultHttpClient(); 
       HttpPost request = new HttpPost(); 
       request.setURI(new URI(url)); 

       List<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 
       postParameters.add(new BasicNameValuePair("param1", "value of param1")); 

       UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);   

       request.setEntity(formEntity); 
       HttpResponse response = client.execute(request); 

       String line; 

       br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
       while ((line = br.readLine()) != null) 
       { 
        sb.append(line + "\n"); 
       } 
       br.close(); 

      } 
      catch(Exception e) 
      { 
       Toast.makeText(HttpPostActivity.this, "Exception: " + e.toString(), Toast.LENGTH_LONG).show(); 
      } 
      finally 
      { 
       if (br != null) 
       { 
        try 
        { 
         br.close(); 
        } 
        catch(IOException ioe) 
        { 
         ioe.printStackTrace(); 
        } 
       }   

      }   

      return(sb.toString()); 
     } 


     protected void onPostExecute(String result) 
     { 
      txtContent.setText(result); 
     } 

您還需要實現onPostExecute。還有其他APIS。

Android Async Task Documentation

+0

感謝您的回答! –

0

嘗試打印出例外。 使用此代碼打印出您的回覆。檢查回覆的狀態

 HttpResponse response = client.execute(request); 

     String line; 

     br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
     while ((line = br.readLine()) != null) 
     { 
      sb.append(line + "\n"); 
     } 
     br.close(); 

    } 
    catch(Exception e) 
    { 
     Toast.makeText(HttpPostActivity.this, "Exception: " + e.toString(), Toast.LENGTH_LONG).show(); 
    } 

告訴我們例外情況。那麼很容易找出你的問題。

編輯答案:

您正在嘗試在主線程中進行聯網操作。這是一件非法的事情。創建一個AsyncTask,即創建一個獨立的線程來完成您的網絡操作。

Android Details of the exception

Stackoverflow question

+0

我使用了你的代碼。我得到了下面的異常 - android.os.NetworkOnMainThreadException –

+0

檢查我更新的答案。如果您需要幫助創建異步任務線程。讓我知道 – rockstar

+0

rockstar感謝您的答案。是的,即使我已經斷定網絡操作正在主線程上執行(不知道這是不允許的)。無論如何,我會盡快查看你給我的鏈接。與此同時,你能否告訴我如何使用AsyncTask,將其添加到上面提供的代碼中。這將是最好的! –

1

在你上面的註釋表明,你得到一個android.os.NetworkOnMainThreadException

在Android的最新版本中,您不允許在主線程上進行聯網,因爲它會導致UI無響應。使用AsyncTasksee the Android developer guide for details)或其他一些機制將代碼移動到其他線程。

+0

是的。感謝您的回答。我相信這是NetworkOnMainThreadException。你如何建議我在我的代碼中實現AsyncTask?你可以自己將它實現到代碼中,並把它作爲答案嗎?這樣,我可以立即使用它,並可以給你一個1+的答案! –

+0

@AdvaitS我已經添加了關於如何使用AsyncTasks的開發人員網站文檔的鏈接。在搖滾明星聯繫的SO問題中也有一個例子。基本上你創建了一個擴展'AsyncTask'的類,把你的網絡代碼放在'doInBackground'方法中,返回結果,然後用'onPostExecute'方法更新UI。然後你只需要創建一個實例並調用'execute'。 –

相關問題