一尘不染

如何将String数组作为基本名称值对发送为HTTPPOST?

json

我想将数组作为名称值对发送为httppost。我的服务器仅接受数组值。以下是我的代码段。

public String SearchWithType(String category_name, String[] type,int page_no) {

    String url = "http://myURL";
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);

    String auth_token = Login.authentication_token;
    String key = Login.key;

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("authentication_token",
                auth_token));
        nameValuePairs.add(new BasicNameValuePair("key", key));
        nameValuePairs.add(new BasicNameValuePair("category_name",
                category_name));
        int i = 0;
        nameValuePairs.add(new BasicNameValuePair("type", type[i]));
        nameValuePairs.add(new BasicNameValuePair("page", String.valueOf(page_no)));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        eu = EntityUtils.toString(entity).toString();

    } catch (IOException ioe) {
        String ex = ioe.toString();
        return ex;
    }

    return eu;
}

阅读 530

收藏
2020-07-27

共1个答案

一尘不染

我知道了 这是如何做:

try {
    int i = 0;

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("authentication_token", auth_token));
    nameValuePairs.add(new BasicNameValuePair("key", key));
    nameValuePairs.add(new BasicNameValuePair("category_name", category_name));
    nameValuePairs.add(new BasicNameValuePair("type", type[i]));
    nameValuePairs.add(new BasicNameValuePair("page", String.valueOf(page_no)));

    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();

    eu = EntityUtils.toString(entity).toString();
} catch (Exception e) {
    Log.e(TAG, e.toString());
}

我要做的就是初始化一个循环:

for (int i = 0; i < type.length; i++) {
    nameValuePairs.add(new BasicNameValuePair("type[]",type[i]));
}
2020-07-27