Java 如何在android中使用volley发送参数数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28272248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:53:51  来源:igfitidea点击:

how to send array of params using volley in android

javaandroidjsonandroid-volley

提问by TechChain

I am developing an application which send lot of data to server.Now i want to send an array of params to a php page using volley.But i am not able to send it.

我正在开发一个向服务器发送大量数据的应用程序。现在我想使用 volley 将一组参数发送到 php 页面。但我无法发送它。

Code for adding params as Array.

将参数添加为数组的代码。

String[] arr =new String[7];
    for(int i=1;i<=7;i++)
    {
        arr[i]="questionId_"+i+"_"+"ans_"+i;

    }
    HashMap<String ,String[]> params=new HashMap<String, String[]>(7);
    params.put("params", arr);

Code for making request to server

向服务器发出请求的代码

RequestQueue que=Volley.newRequestQueue(this);

     final ProgressDialog dialog = new ProgressDialog(HealthMyHistory.this);
     dialog.setTitle("Please Wait");
     dialog.setMessage("Sending Data");
     dialog.setCancelable(false);
     dialog.show();


    CustomJobjectRequest jsObjRequest = new CustomJobjectRequest(Method.POST, url, params, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response)
                {
                    dialog.dismiss();



                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError response) {

                    dialog.dismiss();
                    Toast.makeText(getApplicationContext(), "Unable to Send Data!"+" "+response.toString(), Toast.LENGTH_SHORT).show();
                }
            });
    que.add(jsObjRequest);

}



Problem is in CustomJobjectRequest there is no constructor available of type in which Hashmap accepts string & array as argument.How to do it ? 

Code or CustomJsonObjectRequest

代码或 CustomJsonObjectRequest

 package com.example.healthcoach.data;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;


public class CustomJobjectRequest extends Request<JSONObject>{

    private Listener<JSONObject> listener;
    private Map<String, String> params;

    public CustomJobjectRequest(String url, Map<String, String> params,
              Listener<JSONObject> reponseListener, ErrorListener errorListener) {
          super(Method.POST, url, errorListener);
          this.listener = reponseListener;
          this.params = params;
    }

    public CustomJobjectRequest(int method, String url, Map<String, String> params,
              Listener<JSONObject> reponseListener, ErrorListener errorListener) {
          super(method, url, errorListener);
          this.listener = reponseListener;
          this.params = params;
      }

  public CustomJobjectRequest(int post, String url,
            HashMap<String, String[]> params2, Listener<JSONObject> listener2,
            ErrorListener errorListener) {
        // TODO Auto-generated constructor stub
    }

@Override
  protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
    return params;
  };

  @Override
  protected void deliverResponse(JSONObject response) {
      listener.onResponse(response);
  }

  @Override
  protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
       try {
              String jsonString = new String(response.data,
                      HttpHeaderParser.parseCharset(response.headers));
              return Response.success(new JSONObject(jsonString),
                      HttpHeaderParser.parseCacheHeaders(response));
          } catch (UnsupportedEncodingException e) {
              return Response.error(new ParseError(e));
          } catch (JSONException je) {
              return Response.error(new ParseError(je));
          }
  }

}

采纳答案by ρяσ?ρ?я K

Use

HashMap<String ,String> params=new HashMap<String, String>(7);
for(int i=1;i<=7;i++)
{
    params.put("params_"+i, arr[i]);
}

in CustomJobjectRequestclass because currently you are using Stringtype as value in Map in CustomJobjectRequestclass but sending String[]type when create object of CustomJobjectRequestclass.

CustomJobjectRequest类中,因为当前您在类中使用String类型作为 Map 中的值,CustomJobjectRequestString[]在创建CustomJobjectRequest类对象时发送类型。

Edit:

编辑:

To send all values in single parameter to server use JSONObject.Create a json object using all key-value as:

要将单个参数中的所有值发送到服务器,请使用JSONObject.Create a json object using all key-value as:

 JSONObject jsonObject=new JSONObject();
 for(int i=1;i<=7;i++)
    {
        arr[i]="questionId_"+i+"_"+"ans_"+i;
        jsonObject.put("params_"+i,arr[i]);
    }
HashMap<String ,String> params=new HashMap<String, String>();
params.put("params",jsonObject.toString());

TO send all values on server side get paramsand convert to JSON object and iterate to get all values

在服务器端发送所有值获取params并转换为 JSON 对象并迭代以获取所有值

回答by AnhSang

Use

    Map<String, String> postParam = new HashMap<>();
    int i=0;
    for(String object: friendIds){
        postParam.put("friendIds["+(i++)+"]", object);
        // you first send both data with same param name as friendnr[] ....  now send with params friendnr[0],friendnr[1] ..and so on
    }

this work for me, hope it work to you.

这对我有用,希望对你有用。

回答by taman neupane

Use google json Library to make json array.

使用 google json 库制作 json 数组。

 compile 'com.google.code.gson:gson:2.6.2'

And this code is to put json array in the body of the request

而这段代码就是把json数组放到请求正文中

private void sendTokenToServer(final String jsonArrayString) {
        String tag_string_req = "string_req";
        String url = Const.SEND_TOKEN_TO_SERVER;


        final StringRequest strReq = new StringRequest(Request.Method.POST,
                url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, response.toString());
                hideProgressDialog();
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hideProgressDialog();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> header = new HashMap<>();
                header.put("Content-Type", "application/json; charset=utf-8");
                return header;
            }


            @Override
            public String getBodyContentType() {
                return "application/json; charset=utf-8";
            }

            @Override
            public byte[] getBody() throws AuthFailureError {
                try {
                    return jsonArrayString.getBytes("utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return null;
            }

        };
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

回答by android_jain

Step 1

第1步

Make json param

制作json参数

 Map<String, String> jsonParams = new HashMap<>();

Step 2

第2步

Make set or Arraylist why set or arraylist because no need to put fixed lenth

设置或数组列表为什么设置或数组列表因为不需要固定长度

  private Set<String>  arr;
  for(int i=1;i<=7;i++)
    {
        arr[i]="questionId_"+i+"_"+"ans_"+i;
        arr.add("params_"+i,arr[i]);
    }

Step 3 pass set object as a string

第 3 步将 set 对象作为字符串传递

 if (arr!= null) {
       jsonParams.put("param", arr.toString());
                  }