2013-03-21 123 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