使用POST android发送数组

时间:2014-03-27 07:56:18

标签: android

如何像这样使用POST发送数组

"survey_pages": [{
    "id": 1,
    "answers": [
        {"question": 4, "answer": true}, 
        {"question": 2, "answer": 1}, 
        {"question": 3, "answer": 1}, 
        {"question": 1, "answer": "2014-03-18T00:01:30"}
    ]
}]

这里是我发送数据的代码:

           List<NameValuePair> params = new ArrayList<NameValuePair>();

            params.add(new BasicNameValuePair("token", mSettings.getString("token", "")));
            params.add(new BasicNameValuePair("survey_pages[id]", _survey_id));
            //params.add(new BasicNameValuePair("id", _page_id));
            int listSize = _q_list.size();
            for (int i = 0; i<listSize; i++) {
                  question = question_list.get(i).id;
                  params.add(new BasicNameValuePair("answers[question]", question));
                  params.add(new BasicNameValuePair("answers[answer]", "true"));
            }               

2 个答案:

答案 0 :(得分:1)

取自here

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

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

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

答案 1 :(得分:0)

创建名称值对后,您只需要这两行代码

 httppost.setEntity(new UrlEncodedFormEntity(params ));

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