1

我创建了一个简单的教程将数据发送到服务器

我在 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()

当我尝试按下按钮时,当我尝试刷新页面时,网络服务器没有结果。页面是空白的,没有结果。

这是我的php代码

<?php

//code to reverse the string

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

echo $reversed;

?>

如何解决?

4

1 回答 1

0

First of all, NEVER perform network actions on the UI Thread. It will make your app unresponsive.

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

that actually returns an HttpResponse, not a String. Do this instead:

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 will contain your server response.

And please, next time at least try doing some ex.printStackTrace() on your catch blocks so you know what's going on.

于 2013-03-21T12:25:37.050 回答