如何在Android中的onPageFinished上正确执行HttpPost

时间:2014-06-27 12:03:50

标签: java php android http-post

在我的应用程序中,我有一个WebView。如果加载此WebView,我想执行HttpPost从脚本中获取变量。但是我一直收到异常错误,这告诉我需要在HttpPost中执行AsyncTask。我不知道该怎么做,因为我在Android开发方面做得还不错。

这是我写的HttpPost

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new;   
HttpPost("myscript.php");

    try {
       // Add your data
       List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
       nameValuePairs.add(new BasicNameValuePair("website", "google.com"));
       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

       // Execute HTTP Post Request
       HttpResponse response = httpclient.execute(httppost);

       // writing response to log
       Log.d("Http Response:", response.toString());

     } catch (ClientProtocolException e) {
       // TODO Auto-generated catch block
     } catch (IOException e) {
       // TODO Auto-generated catch block
     }

这是我的onPageFinished方法:

myWebView.setWebViewClient(new WebViewClient()
{

    @Override
    public void onPageFinished(WebView myWebView, String url)
    {

        myWebView.loadUrl("javascript:(function() { " +
        "var tetsttest = document.getElementById('menu-toggle'); tetsttest.style.display = 'none'; tetsttest.style.display = 'none'; tetsttest.style.display = 'none';" +
        "})()");

        // when a page has finished loading dismiss any progress dialog
        if (progressDialog != null && progressDialog.isShowing())
        {
            progressDialog.dismiss();
        }
     }
}); 

这是php文件:

<?php

        $website = $_POST['website'];

    $conn = mysql_connect("localhost", "username", "password") or die("err");
    $db = mysql_select_db('database') or die("err");

    $sql = "SELECT color FROM colors WHERE website='$website'";
    $result = mysql_query($sql) or die(mysql_error());
    $row = mysql_fetch_array($result);
    $color = $row['color'];

    print "$color";

?>

1 个答案:

答案 0 :(得分:1)

android中的所有网络操作都需要在一个单独的线程中执行,而AsyncTask是一个允许你以优雅的方式执行线程的类(无痛的线程)。下面是asynctask的一个例子:

public class SendRequestAsyncTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        //runs in ui thread 
    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
        //perform network operations here it is the background thread
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        //runs in ui thread you can update the layout here
    }
}

在你的onpageloading完成方法上,你可以像这样调用这个asynctask:

new SendRequestAsyncTask().execute();