将数据http发送到网络服务器没有结果

时间:2013-03-21 12:20:36

标签: android

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

我在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;

?>

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

首先,从不在UI线程上执行网络操作。它会让你的应用无响应。

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

实际上返回一个HttpResponse,而不是一个String。这样做:

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将包含您的服务器响应。

请下次,至少尝试在你的catch块上做一些ex.printStackTrace(),这样你就知道发生了什么。