Http帖子使用AsyncTask和NameValuePairs

时间:2013-07-30 15:16:31

标签: android android-asynctask http-post

我有一个需要将一些数据发送到服务器的应用程序。我创建一个Connection类来处理该进程。以下是我的代码:

private class Connection extends AsyncTask<ArrayList<NameValuePair>, Void, Void>{

    protected Void doInBackground(ArrayList<NameValuePair>... nameValuePairs){

        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.xxxx.com/postdata.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

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

            Log.i("postData", response.getStatusLine().toString());
        }
        finally{}

    }

}

但是,我收到以下错误:“构造函数UrlEncodedFormEntity(ArrayList [])未定义”。我是Android的新手,我不知道导致错误的是什么。非常感谢!

1 个答案:

答案 0 :(得分:1)

private class Connection extends AsyncTask<ArrayList<NameValuePair>, Void, Void>{

    protected Void doInBackground(ArrayList<NameValuePair>... nameValuePairs){
        // get zero index of nameValuePairs and use that to post
        ArrayList<NameValuePair> nvPairs = nameValuePairs[0];

        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.xxxx.com/postdata.php");
            httppost.setEntity(new UrlEncodedFormEntity(nvPairs));

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

            Log.i("postData", response.getStatusLine().toString());
        }
        finally{}

    }

}