【问题标题】:how to send array of params using volley in android如何在android中使用凌空发送参数数组
【发布时间】:2015-02-02 06:32:43
【问题描述】:

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

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

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);

向服务器发出请求的代码

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 ? 

代码或 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));
          }
  }

}

【问题讨论】:

  • CustomJobjectRequest class 你自己的班级?请显示代码
  • @prosper K 请检查我的代码
  • 查看我的编辑答案,这可能是您想要的

标签: java android json android-volley


【解决方案1】:

使用

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

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

编辑:

要将单个参数中的所有值发送到服务器,请使用JSONObject。使用所有键值对创建一个 json 对象:

 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());

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

【讨论】:

  • 为什么我不能在 CustomJsonObjectRequest 类中创建一个接受 HashMap 的构造函数?
  • @TechGuy: getParams() 或您从Request&lt;JSONObject&gt; 类中使用的其他方法是使用Map&lt;String ,String&gt; 而不是HashMap&lt;String ,String[]&gt;,因此您应该使用Hash&lt;String ,String&gt;
  • 好的,这是发送参数数组的唯一方法吗?
  • @prosper K 先生,我想像 php 一样在服务器端获取一组参数
  • @TechGuy:无法将数组作为参数传递,但您可以使用 JSONObject 在单个参数中发送所有值。创建一个包含所有值的 JSONObject,然后将其作为 HashMap&lt;String ,String&gt; params=new HashMap&lt;String, String&gt;();params.add("params", jsonobject.toString()); 发送到服务器现在在 php 端将接收到的字符串从 params 转换为 JSONObject 以获取所有值
【解决方案2】:

使用

    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
    }

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

【讨论】:

    【解决方案3】:

    使用google json库制作json数组。

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

    而这段代码是把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);
        }
    

    【讨论】:

      【解决方案4】:

      第一步

      制作json参数

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

      第 2 步

      为什么要设置set或arraylist,因为不需要放置固定的lenth

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-25
        相关资源
        最近更新 更多