0

我可以通过使用普通 get post 方法的 volley 库来使用 api,但我的 php 团队刚刚更改了我的 api 接受 json 。我知道有JsonObjectrequestvolley但我不知道如何将参数放入`JsonObjectRequest. 任何帮助都会得到帮助。

PHP API

<?php 
if($_SERVER['REQUEST_METHOD']=='POST'){
$data_back = json_decode(file_get_contents('php://input'));
header("Content-type: application/json");
require "conn.php";
$id = $data_back->{"id"};
$address = $data_back->{"address"};
$pincode = $data_back->{"pincode"};
$name = $data_back->{"name"};
$mobile = $data_back->{"mobile"};

$sql = "UPDATE tbl_addressbook SET name = '$name', address = '$address', pincode = '$pincode', mobile = '$mobile' WHERE  id = $id";

if(mysqli_query($conn,$sql)){
    echo 'Address Book Updated Successfully';
}
else{
   echo 'Could Not Update Your Address Book';
  }
}
?> 

排球请求

StringRequest stringRequest=new StringRequest(Request.Method.POST, Config.UPDATE_ADDRESS_BOOK,
                                new Response.Listener<String>() {
                                    @Override
                                    public void onResponse(String response) {
                                        Toast.makeText(mContext,"Address Changed",Toast.LENGTH_LONG).show();
                                        list.set(getAdapterPosition(),new AddressBookModel(bookModel.getId(),
                                                etName.getText().toString(),
                                                etAddress.getText().toString(),
                                                etPinCode.getText().toString(),
                                                etPhone.getText().toString(),
                                                bookModel.getDefAddress()));
                                        d.dismiss();
                                        progress.dismiss();
                                        ((Activity)mContext).runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                notifyDataSetChanged();
                                            }
                                        });
                                    }
                                }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Toast.makeText(mContext,"Something Went Wrong \n ttry again later",Toast.LENGTH_LONG).show();
                            }
                        }){
                            @Override
                            protected Map<String, String> getParams() throws AuthFailureError {
                                Map<String, String> map=new HashMap<String, String>();
                                map.put("id",bookModel.getId());
                                map.put("name",etName.getText().toString());
                                map.put("address",etAddress.getText().toString());
                                map.put("pincode",etPinCode.getText().toString());
                                map.put("phone",etPhone.getText().toString());
                                return checkParams(map);
                            }
                            private Map<String, String> checkParams(Map<String, String> map){
                                Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
                                while (it.hasNext()) {
                                    Map.Entry<String, String> pairs = (Map.Entry<String, String>)it.next();
                                    if(pairs.getValue()==null){
                                        map.put(pairs.getKey(), "");
                                    }
                                }
                                return map;
                            }
                        };
                        VolleySingleton.getInstance(mContext).addToRequestQueue(stringRequest);
4

3 回答 3

2

首先创建你的 JsonObject 像

    JSONObject js = new JSONObject();
    try {
        js.put("email", "adasda");
        js.put("address", "adasd");
        js.put("pincode", "adadasd");

    }catch (JSONException e) {
            e.printStackTrace();
    }

然后是您的 JSON 请求,仔细查看获取标头。

    JsonObjectRequest jsonObjReq = new JsonObjectRequest(
    Request.Method.POST,url, js,
    new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.d(TAG, response.toString());

            msgResponse.setText(response.toString());
            hideProgressDialog();
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            hideProgressDialog();
        }
    }) {

/**
 * Passing some request headers
 * */
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
     HashMap<String, String> headers = new HashMap<String, String>();
     headers.put("Content-Type", "application/json; charset=utf-8");
    return headers;
}
于 2017-02-06T11:59:10.847 回答
2

简单的奶酪柠檬汁!

一些代码

HashMap<String, String> params = new HashMap<String, String>();
params.put("id", "300");
params.put("address", "Mars");
params.put("pincode", "***");
params.put("name", "Jon Skeet");
params.put("mobile", "911");
JsonObjectRequest request = new JsonObjectRequest(
                            /*URL*/, 
                            new JSONObject(params),
                            new Response.Listener<JSONObject>(){/*...*/});
于 2017-02-06T12:25:45.463 回答
-2

私人无效getWalletDetails(){

    final ProgressDialog  pDialog;  // = new ProgressDialog(mcontext);
    StringRequest stringRequest;

    pDialog = GifDialog.ctor(mcontext);
    pDialog.show();

    stringRequest = new StringRequest(Request.Method.POST, place your url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    //Disimissing the progress dialog
                    pDialog.dismiss();
                    //Showing toast message of the response

                    try {

                        JSONObject jsonObject = new JSONObject(s);

                        totbal.setText("\u20B9 "+jsonObject.getString("avail_balance"));
                        JSONArray jsonArray = jsonObject.getJSONArray("tx_detail");

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

                            JSONObject object = jsonArray.getJSONObject(i);
                            mode = new Model_Wallet_Transaction();
                            mode.setStr1(object.getString("date"));
                            mode.setStr4(object.getString("insert_time"));
                            mode.setStr2(object.getString("name"));

                            mode.setStr3(object.getString("transaction_id_no"));
                            mode.setAmount(object.getString("amount"));
                            mode.setTxtype(object.getString("tx_type"));
                            modlist.add(mode);
                        }
                        // Collections.sort(modlist, new StringDateComparator());
                        adp = new CustomAdapter_Wallet_Transaction(getApplicationContext(), modlist);
                        list.setAdapter(adp);

                    } catch (Exception e) {

                        Log.e("Error", e.toString());
                    }
                    // Toast.makeText(Wallet_Transaction.this, s, Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    //Dismissing the progress dialog
                    pDialog.dismiss();
                    //Showing toast
                    //Toast.makeText(Wallet_Transaction.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
                }

            }) {

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

            //Creating parameters
            Map<String, String> params = new Hashtable<String, String>();
            //Adding parameters
            params.put("user_id", UserId);           
            params.put("deviceId", DeviceId);

            return params;
        }
    };

    //Creating a Request Queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    //Adding request to the queue
    requestQueue.add(stringRequest);
}
于 2017-02-06T12:12:35.953 回答