3

我是 Json 解析的新手。我正在尝试使用读取 json 数据,JsonArrayRequest但在发送参数和使用 POST 方法时我有点困惑。如果JsonObjectRequest我可以发送方法类型、url、参数,但JsonArrayRequest如何发送用户名和密码等参数并使用 POST 方法。请帮帮我。这是我写的代码。

final JsonArrayRequest jsonObjReq = new JsonArrayRequest(MySingleton.getInstance().getDOWNLOAD_SERVICES_URL(), new Response.Listener<JSONArray>() {
    @Override
    public void onResponse(JSONArray response) {
        try {
            if(response==null) {
                pDialog.hide();
            }
            for (int i = 0; i < response.length(); i++) {
                jresponse = response.getJSONObject(i);
            }
            //String service_response = response.getString("SvcTypeDsc");
            Toast.makeText(getActivity().getApplicationContext(), "services" + jresponse, Toast.LENGTH_SHORT).show();
        } catch (JSONException e) {
            e.printStackTrace();
            Log.d("soservices", "sos" + e.getMessage());
        }
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyLog.d("Login request", "Error: " + error.getMessage());
        Log.d("Volley Error:", "Volley Error:" + error.getMessage());
        Toast.makeText(getActivity(), "Unable to connect to server, try again later", Toast.LENGTH_LONG).show();
        pDialog.hide();
    }
}) {
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> params = new HashMap<String, String>();
        params.put("uniquesessiontokenid","39676161-b890-4d10-8c96-7aa3d9724119");
        params.put("loginname", userDet.getSAID());
        params.put("password", "23295");
        return super.getParams();
     }

     @Override
     public int getMethod() {
         try {
             getParams();
         } catch (AuthFailureError authFailureError) {
             authFailureError.printStackTrace();
         }
             return super.getMethod();
         }
     };

     AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

}

我的 json 数据是这样的:

{
    "username":"rushi",
    "firstname": "abc",
},
{
    "username": "xyz",
    "firstname": "vxa",
},

参数未发送。请帮我解决这个问题。先感谢您。

4

5 回答 5

3

这解决了我在使用 JsonArrayRequest 和 POST 方法时传递参数的问题。

Volley.newRequestQueue(getActivity())
    .add(new JsonRequest<JSONArray>(Request.Method.POST,
    MySingleton.getInstance().getDOWNLOAD_SERVICES_URL(),
    jsonobj.toString(),
    new Response.Listener<JSONArray>() {
          @Override
          public void onResponse(JSONArray jsonArray) {
              Log.d("response", "res-rec is" + jsonArray);
              if (jsonArray == null) {
                  pDialog.dismiss();
                  Snackbar.make(myview, "No services found", Snackbar.LENGTH_LONG).show();

              } else {


                  for (int i = 0; i < jsonArray.length(); i++) {
                      try {

                          pDialog.dismiss();
                          JSONObject jsonObject = jsonArray.getJSONObject(i);
                          String desc = jsonObject.getString("SvcTypeDsc");
                          String image_url = jsonObject.getString("ThumbnailUrl");
                          // al_ImageUrls.add(image_url);

                          al_list_of_services.add(desc);
                          ad_servicesadapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, al_list_of_services);

                          lv_webservicesList.setAdapter(ad_servicesadapter);

                          Log.d("imageurls", "imagesurl " + image_url);
                          Log.d("services-list", "list is " + desc + " " + i);
                      } catch (JSONException e) {
                          e.printStackTrace();
                      }

                  }
              }
          }
      }, new Response.ErrorListener() {
          @Override
          public void onErrorResponse(VolleyError volleyError) {
              VolleyLog.d("Login request", "Error: " + volleyError.getMessage());
              Log.d("Volley Error:", "Volley Error:" + volleyError.getMessage());
              Toast.makeText(getActivity(), "Unable to connect to server, try again later", Toast.LENGTH_LONG).show();
              pDialog.dismiss();
          }
      })

      {
          @Override
          protected Map<String, String> getParams() throws AuthFailureError {


              Map<String, String> params = new HashMap<String, String>();
              // params.put("uniquesessiontokenid", "39676161-b890-4d10-8c96-7aa3d9724119");
              params.put("uniquesessiontokenid", userDet.getSessionToken());
              params.put("said", userDet.getSAID());
              params.put("SOId", "23295");

              return super.getParams();
          }

          @Override
          protected Response<JSONArray> parseNetworkResponse(NetworkResponse networkResponse) {


              try {
                  String jsonString = new String(networkResponse.data,
                          HttpHeaderParser
                                  .parseCharset(networkResponse.headers));
                  return Response.success(new JSONArray(jsonString),
                          HttpHeaderParser
                                  .parseCacheHeaders(networkResponse));
              } catch (UnsupportedEncodingException e) {
                  return Response.error(new ParseError(e));
              } catch (JSONException je) {
                  return Response.error(new ParseError(je));
              }

              //  return null;
          }
      }
);
于 2015-10-15T10:07:36.183 回答
2
import java.io.UnsupportedEncodingException;
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 CustomRequest extends Request<JSONObject> {

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

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

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

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

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

    @Override
    protected void deliverResponse(JSONObject response) {
        // TODO Auto-generated method stub
        listener.onResponse(response);
    }
}

在活动/片段中使用这个

RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
CustomRequest jsObjRequest = new CustomRequest(Method.POST, url, params, this.createRequestSuccessListener(), this.createRequestErrorListener());

requestQueue.add(jsObjRequest);

答案在这里获取表格。 https://stackoverflow.com/a/19945676/1641556

也参考这些文章。

  1. https://developer.android.com/training/volley/index.html
  2. http://www.androidhive.info/2014/09/android-json-parsing-using-volley/
于 2015-10-08T11:26:59.073 回答
1

如果你正在使用'com.android.volley:volley:1.0.0'你应该覆盖getParams()这样的方法:

public synchronized void addJsonArrayRequest(int method, String url, final JSONObject jsonRequest, Response.Listener<JSONArray> responseListener, Response.ErrorListener errorListener) {
    JsonArrayRequest request = new JsonArrayRequest(method, url, null, responseListener, errorListener) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> params = new HashMap<>();
            try {
                params.put("key1", jsonRequest.getString("key1"));
                params.put("key2", Integer.toString(jsonRequest.getInt("key2")));
                params.put("key3", Boolean.toString(jsonRequest.getBoolean("key3")));
                params.put("key4", jsonRequest.getJSONArray("key4").toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return params;
        }
    };
    addToRequestQueue(request);
}

如果您使用的是“com.mcxiaoke.volley:library:1.0.19”,您可以简单地输入JSONObject

public synchronized void addJsonArrayRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONArray> responseListener, Response.ErrorListener errorListener) {
    JsonArrayRequest request = new JsonArrayRequest(method, url, jsonRequest, responseListener, errorListener);
    addToRequestQueue(request);
}
于 2016-11-11T09:33:51.557 回答
0

这是一个使用 volly 将请求发布到服务器的示例

您可以将参数添加到 HashMap,然后将其传递到您正在创建的请求中;

编辑:

    HashMap<String, String> mRequestParams = new HashMap<String, String>();
    mRequestParams.put("username","abcd");
    mRequestParams.put("password", "123456");

    public void vollyStringRequestForPost() {


   JsonArrayRequest req = new JsonArrayRequest(Request.Method.POST, strURL, new JSONObject(mRequestParams),
                new Response.Listener<JSONArray>() {

                    @Override
                    public void onResponse(JSONArray response) {

                            try {

                               //Here you will receive your response

                            } catch (JSONException e) {

                                e.printStackTrace();

                            }
                        }
                    }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {

                    //Do what you want to do on error
                }
            });



        mRequestQueue.add(req);
    }


}
于 2015-10-08T11:38:24.927 回答
-1

干得好..

final HashMap<String, String> params = new HashMap<String, String>();
    params.put("email", userName);
    params.put("password", password);

    final JSONObject jsonObject = new JSONObject(params);

    JsonArrayRequest req = new JsonArrayRequest(Request.Method.POST, url, jsonObject,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    try {
//process response
}
catch(JSONEXception e){}

在 PHP 方面,您可以像这样获得这些参数

$json=file_get_contents('php://input');

$data = json_decode($json);
$email=$data->{'email'};
$pass=$data->{'password'};
于 2015-10-08T11:26:09.313 回答