通过Android应用程序连接到PHP脚本

时间:2013-05-17 11:59:27

标签: java php android

这是我到目前为止的代码。

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;

3 个答案:

答案 0 :(得分:1)

在上面的评论中,您表示您获得的是android.os.NetworkOnMainThreadException

在最新版本的Android中,您不允许在主线程上进行网络连接,因为它会使UI无响应。使用AsyncTasksee the Android developer guide for details)或其他一些机制将代码移动到其他线程。

答案 1 :(得分: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();
    }

告诉我们例外情况。那么很容易找出你的问题。

编辑:答案:

您正尝试在MAIN线程上执行网络操作。这是非法的事情。创建一个AsyncTask,即创建一个单独的线程来进行网络操作。

Android Details of the exception

Stackoverflow question

答案 2 :(得分:0)

按照海报的要求添加单独的答案。

假设:

a)有一个文本框接受要加载的URL

b)单击一个按钮,对获取的URL

执行网络操作

实现一个调用以下函数的按钮单击侦听器:

    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