2013-03-21 50 views
1

我創建了一個簡單的教程將數據發送到服務器數據發送HTTP到web服務器沒有結果

我裏面的onCreate創建一個按鈕

Button button = (Button) findViewById(R.id.send); 
     button.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       // Perform action on click 

       postData(); 
      } 
     }); 

這裏是我的代碼發送數據

public void postData() { 
     // Create a new HttpClient and Post Header 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://www.www.www/hama/test123.php"); 

     //This is the data to send 
     String MyName = "adil"; //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() 

當我嘗試按下按鈕,當我嘗試刷新頁面時,webserver中沒有任何結果。 頁面空白,沒有結果。

這裏是我的PHP代碼

<?php 

//code to reverse the string 

$reversed = strrev($_POST["action"]); 

echo $reversed; 

?> 

如何解決呢?

回答

0

首先,從不在UI線程上執行網絡操作。它會讓你的應用程序無響應。

String response = httpclient.execute(httppost, responseHandler); 

實際上返回一個HttpResponse,而不是一個字符串。代之以:

final HttpResponse response = httpClient.execute(get, localContext); 

final HttpEntity entity = response.getEntity(); 
final InputStream is = entity.getContent(); 
final InputStreamReader isr = new InputStreamReader(is, "ISO-8859-1"); 
final BufferedReader br = new BufferedReader(isr); 
String line = ""; 
String responseFromServer = ""; 
while ((line = br.readLine()) != null) { 
    responseFromServer += line; 
} 

responseFromServer將包含您的服務器響應。

並請,下次至少嘗試做一些ex.printStackTrace()你的catch塊,讓你知道發生了什麼事。

+0

仍然沒有結果@ santirivera92 – 2013-03-21 12:52:23

+0

是否有任何異常出現?你確定你的php代碼是正確的嗎? – razielsarafan 2013-03-21 14:50:08

+0

它的錯誤關於我的網頁瀏覽器或我的代碼php。當我試圖捕捉到數據庫的帖子它的工作原理,但在刷新頁面的PHP中,數據不會顯示,我試着用你的代碼它也可以。謝謝。 @ santirivera92 – 2013-03-22 01:49:32