getParams() 在 JsonObjectRequest 中不起作用。我想将 String 发送到 php 文件并根据该文件获取 JsonObject

getParams() not working in JsonObjectRequest.. I want to send String to php file and get JsonObject according to that

    @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            View view = inflater.inflate(R.layout.fragment_product, container, false);
            recyclerView = (RecyclerView) view.findViewById(R.id.productRecyclerView);
            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            pAdapter = new ProductAdapter(getActivity());
            recyclerView.setAdapter(pAdapter);
            getJsonRequest();
            return view;
        }   

 private void getJsonRequest() {

            /* JSONObject jsonBody = new JSONObject();//this didn't work
            try {
                jsonBody.put("matGroup", "FG0001");
             } catch (JSONException e) {
                //Do nothing.
              }*/

           /* Uri.Builder b = Uri.parse(AppConfig.URL_JSON_PRODUCT_NEW).buildUpon(); //this didn't work either
            b.appendQueryParameter("matGroup", "FG0001");
            String url = b.build().toString();*/

当我使用 StringRequest 时,字符串被解析为 pHp.I 无法使用 StringRequest,因为我想获得一个 jsonObject

            JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, AppConfig.URL_JSON_PRODUCT, null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    productList = parseJsonResponse(response);
                    pAdapter.setProductList(productList);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    HashMap<String, String> hashMap = new HashMap<String, String>();
                    hashMap.put("matGroup", "FG0001");
                    return hashMap;
                }
            };
            requestQueue.add(request);
        }

这是我的 php 文件。从 getParams 解析的字符串应该分配给 $matGroup

<?php
require_once 'include/Config.php';
//header('Content-Type: application/json');

$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("connection failed");
    mysql_select_db(DB_DATABASE,$con) or die("db selection failed");


//if(isset($_POST['matGroup']))

    $matGroup = $_GET['matGroup'];

    $r=mysql_query("select tbl_inventory.*,tbl_mas_material.des,tbl_mas_material.matgrp from tbl_inventory INNER JOIN tbl_mas_material on tbl_inventory.material=tbl_mas_material.material where tbl_inventory.qty>'0' and matgrp = '$matGroup'");

    $result = array();

        while($row=mysql_fetch_array($r)){
        array_push($result,
        array('material'=>$row[0],
       'plant'=>$row[1],'qty'=>$row[3],'ton'=>$row[4],'val'=>$row[5],'des'=>$row[6],'matgrp'=>$row[7]));}

        echo json_encode(array("feed"=>$result));


    mysql_close($con);


?>

您必须使用 CustomJSONRequest,因为 getParams() 不会调用,因为 JsonObjectRequest 扩展了直接调用 getBody() 的 JsonRequest,将构造函数的第二个参数(调用 requestBody)编码为 contentType ,这就是它忽略您的 getParam() 方法的原因。

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

并且您将 Custom Request 称为

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

requestQueue.add(jsObjRequest);

原文Post:

希望对您有所帮助。

更新

StringRequest request = new StringRequest(Request.Method.POST,
                AppUrls.URL_SAVE_DATA, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject json = new JSONObject(response);
                    String status = "";
                    if(json != null && json.has(JSONParsor.STATUS))
                        status = json.getString(JSONParsor.STATUS);
                    if(status != null && status.length() > 0 && status.equalsIgnoreCase("success")) {                    }
                } catch (JSONException e) {
                    Log.d("JSON Exception", e.toString());
                }
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if(error == null) {

                }
            }
        })

        {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(KEY_PICTURE_NAME, picture.getFileName());
                params.put(KEY_SECTION_ID, picture.getSectionId() + "");
                return params;

            }

        };

        request.setTag(SAVE_DATA);
        addToRequestQueue(request);

希望对您有所帮助