如何使用Asynchronous和onPostExecute向PHP发送值并获取响应

时间:2015-02-28 13:24:23

标签: java android

如何使用异步 HttpRequest 向php页面发送值并获得响应,然后使用 OnPostExcute 对其执行某些操作。

Java

private class MyAsyncTask extends AsyncTask<String, Integer, Double>{

    @Override
    protected Double doInBackground(String... params) {
        // TODO Auto-generated method stub
        postData(params[0]);
        return null;
    }

    protected void onPostExecute(Double result){
        pb.setVisibility(View.GONE);
        // Do something with the response here
        // ....
    }

    public void postData(String valueIWantToSend) {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("__url_to_file.php");

        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
    }

}

PHP

<?php
    // return the value back to the app
    echo $_POST["myHttpData"];

?>

1 个答案:

答案 0 :(得分:2)

private class MyAsyncTask extends AsyncTask<String, HttpResponse, HttpResponse>{

        @Override
        protected HttpResponse doInBackground(String... params) {
            // TODO Auto-generated method stub
            return postData(params[0]);
        }

        protected void onPostExecute(HttpResponse result){
            View pb;
            pb.setVisibility(View.GONE);

            HttpEntity entity = result.getEntity();
            String responseString = EntityUtils.toString(entity, "UTF-8");
            Toast.makeText(mContext, responseString, Toast.LENGTH_LONG).show();
        }

        @SuppressWarnings("unchecked")
        public HttpResponse postData(String valueIWantToSend) {
            // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("__url_to_file.php");

            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
            httppost.setEntity(new UrlEncodedFormEntity((List<? extends org.apache.http.NameValuePair>) nameValuePairs));

            HttpResponse response = httpclient.execute(httppost);
            return response;
        }

    }

你可以用上面的东西做点什么。这肯定会将HttpResponse传递给onPostExecute方法,并允许你对它做一些事情。

我看看这一行,但是:

httppost.setEntity(new UrlEncodedFormEntity((List<? extends org.apache.http.NameValuePair>) nameValuePairs));

因为它对我来说似乎不对。我必须添加强制转换才能使编译器满意。这可能不是理想的结果(但是要让ASyncTask允许处理HttpResponse的重点)。