繁体   English   中英

使用Android Volley中的POST方法将对象作为数据发送?

[英]Send Object as Data with POST Method in Android Volley?

我正在使用POST方法,并尝试使用Android Volley Library将“当前密码”更改为“ New One”以将对象作为数据发送,但是我无法做到这一点。

设置片段

  public class SettingFragment extends Fragment implements View.OnClickListener {
    EditText userName, oldPassword, newPassword;
    String Navigation_URL_SettingRequest = "http://192.168.100.5:84/api/usersApi/updateByMasterID";
    String username, oldpassword, newpassword;
    String master_id, Name, access_token;

    Button save, reset;
    public static final String KEY_Name = "NAME";
    public static final String KEY_USERNAME = "UserName";
    public static final String KEY_OldPASSWORD = "oldPassword";
    public static final String KEY_UserPassword = "UserPassword";
    public static final String KEY_MasterID = "MasterID";


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_setting, container, false);
        setHasOptionsMenu(true);

        userName = (EditText) view.findViewById(R.id.setting_username);
        oldPassword = (EditText) view.findViewById(R.id.setting_oldpassword);
        newPassword = (EditText) view.findViewById(R.id.setting_newpassword);
        save = (Button) view.findViewById(R.id.setting_save);
        reset = (Button) view.findViewById(R.id.setting_reset);

        SessionManagement session = new SessionManagement(getContext());
        session.checkLogin();
        access_token = session.getAccesstToken();
        master_id = session.getMasterId1();
        System.out.println(master_id);
        Name = session.getKeyName();

        save.setOnClickListener(this);
        return view;
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Auto-generated method stub
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.dashboard, menu);
    }


    private void makeJsonSettingRequest() throws JSONException {


        username = userName.getText().toString().trim();
        oldpassword = oldPassword.getText().toString().trim();
        newpassword = newPassword.getText().toString().trim();


     /*
        // JSONObject js = new JSONObject();
        try {
            RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
            String URL = "http://192.168.100.5:84/api/usersApi/updateByMasterID";
            JSONObject jsonBody = new JSONObject();
            jsonBody.put(KEY_USERNAME, username);
            jsonBody.put(KEY_OldPASSWORD, oldpassword);
            jsonBody.put(KEY_UserPassword, newpassword);
            jsonBody.put(KEY_MasterID, master_id);
            jsonBody.put(KEY_Name, Name);
            final String requestBody = jsonBody.toString();

            StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.i("VOLLEY", response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("VOLLEY", error.toString());
                    //  error.getMessage();

                }
            }) {
                @Override
                public String getBodyContentType() {
                    return "Content-Type;application/x-www-form-urlencoded";
                }

                @Override
                public byte[] getBody() throws AuthFailureError {
                    try {
                        return requestBody == null ? null : requestBody.getBytes("utf-8");
                    } catch (UnsupportedEncodingException uee) {
                        VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                        return null;
                    }
                }

                @Override
                protected Response<String> parseNetworkResponse(NetworkResponse response) {
                    String responseString = "";
                    if (response != null) {
                        responseString = String.valueOf(response.statusCode);
                        // can get more details such as response.headers
                    }
                    return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
                }
            };

            requestQueue.add(stringRequest);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    */


        //   JSONObject params = new JSONObject();
        //   params.put(KEY_Name, Name);
        //   params.put(KEY_MasterID, master_id);
        //   params.put(KEY_USERNAME, username);
        //   params.put(KEY_OldPASSWORD, oldpassword);
        //   params.put(KEY_UserPassword, newpassword);


        StringRequest stringRequest = new StringRequest(Request.Method.POST, Navigation_URL_SettingRequest,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.i("VOLLEY", response);

                        // VolleyLog.v("Response:%n %s", response.toString(4));


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

                        System.out.println("This is an Error mate");


                    }
                }) {


            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                // headers.put("Authorization", "Bearer " + access_token);
                //  headers.put("Authorization",   access_token);
                //  headers.put("Content-Type", "application/x-www-form-urlencoded");

                //  headers.put("Content-Type", "application/json");

                //   headers.put(KEY_Name, Name);
                //   headers.put(KEY_MasterID, master_id);
                //   headers.put(KEY_USERNAME, username);
                //   headers.put(KEY_OldPASSWORD, oldpassword);
                //   headers.put(KEY_UserPassword, newpassword);


                return headers;
            }

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
                //JSONObject content = new JSONObject();

                try {


                    map.put(KEY_USERNAME, username);
                    map.put(KEY_OldPASSWORD, oldpassword);
                    map.put(KEY_UserPassword, newpassword);
                    map.put(KEY_MasterID,   master_id);
                    map.put(KEY_Name, Name);


                    Log.d("Success", map.put(KEY_USERNAME, username));

                } catch (Exception e) {

                    e.printStackTrace();
                }


                //map.put("access_token", accesstoken);
                //  map.put("grant_type", "password");
                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));


        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(stringRequest);


    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // handle item selection
        switch (item.getItemId()) {
            case R.id.action_settings:
                // do s.th.
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }


    @Override
    public void onClick(View v) {
        try {
            makeJsonSettingRequest();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

后端对象看起来像

  Users = {
           NAME: vm.name,
           UserName: vm.currentUserName,
           oldPassword:vm.oldPassword,
           UserPassword: vm.UserPassword
           Users.MasterID = vm.masterID;
       }       

我可以通过POSTMan发送,但无法通过代码发送。

在此处输入图片说明

日志猫

05-29 16:16:49.764 1114-2077/com.example.user.mis E/Volley: [651] BasicNetwork.performRequest: Unexpected response code 404 for http://192.168.100.5:84/api/usersApi/updateByMasterID

该问题如何解决?

您可以尝试使用此代码,我已经实现了与您相同的操作……可能对您有用

private void makeJsonSettingRequest() throws JSONException {


        username = userName.getText().toString().trim();
        oldpassword = oldPassword.getText().toString().trim();
        newpassword = newPassword.getText().toString().trim();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Navigation_URL_SettingRequest,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.i("VOLLEY", response);


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

                        System.out.println("This is an Error mate");


                    }
                }) {


            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();

                headers.put(KEY_Name, Name);
                headers.put(KEY_MasterID, master_id);
                headers.put(KEY_USERNAME, username);
                headers.put(KEY_OldPASSWORD, oldpassword);
                headers.put(KEY_UserPassword, newpassword);
                return headers;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);


    }

您还可以使用StringRequest将POST parameters作为JSONObject发送。

试试这个:

    private static final String KEY_Name = "NAME"
    private static final String KEY_MasterID = "MasterID"
    private static final String KEY_USERNAME = "UserName"
    private static final String KEY_OldPASSWORD = "oldPassword"
    private static final String KEY_UserPassword= "UserPassword"

    ..........
    ..................

    JSONObject params = new JSONObject();
    params.put(KEY_Name, Name);
    params.put(KEY_MasterID, master_id);
    params.put(KEY_USERNAME, username);
    params.put(KEY_OldPASSWORD, oldpassword);
    params.put(KEY_UserPassword, newpassword);

    StringRequest stringRequest = new StringRequest(Request.Method.POST, 
            Navigation_URL_SettingRequest, params, 
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.i("VOLLEY", response);

                    // VolleyLog.v("Response:%n %s", response.toString(4));
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    System.out.println("This is an Error mate");
                }
            }) 
    {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<String, String>();
            // headers.put("Authorization", "Bearer " + access_token);
            // headers.put("Authorization",   access_token);
            // headers.put("Content-Type", "application/x-www-form-urlencoded");
            // headers.put("Content-Type", "application/json");
            return headers;
        }
    };

    stringRequest.setRetryPolicy(new DefaultRetryPolicy(
            60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));


    RequestQueue requestQueue = Volley.newRequestQueue(getContext());
    requestQueue.add(stringRequest);

    ..............
    ...................

在后端中使用JSON对象时,应将StringRequest更改为JSONObjectRequest。 因此,您应该将字符串作为JSON对象传递,然后它可能会起作用。

 private void makeJsonObjectRequest() throws JSONException {
    JSONObject cred = new JSONObject();
    cred.put("username", username.getText().toString());
    cred.put("password", password.getText().toString());

    JsonObjectRequest jsonObjReq = new 
    JsonObjectRequest(Request.Method.POST,
            urlJsonPost, cred, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            Log.d(TAG, response.toString());
            //aftererror:
            try {
                // Parsing json object response
                // response will be a json object
                token = response.getString("token");
                adminName = response.getString("adminName");
                jsonResponse = "";
                jsonResponse += "token:" + token ;
                jsonResponse += "adminName:" + adminName;

                txtResponse.setText(jsonResponse);


            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(),
                        "Error: " + e.getMessage(),
                        Toast.LENGTH_LONG).show();
            }
            hidepDialog();
 }
}, new Response.ErrorListener() {
           @Override
            public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
            error.getMessage(), Toast.LENGTH_SHORT).show();
      }});AppController.getInstance().addToRequestQueue(jsonObjReq);   

您还需要创建一个名为AppController.java的类,并在下面的代码中打孔

import android.app.Application;
import android.text.TextUtils;import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.toolbox.Volley;public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();

private RequestQueue mRequestQueue;

private static AppController mInstance;

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;
}

public static synchronized AppController getInstance() {
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
}

}

你可以试试这个

 try {
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    String URL = "http://...";
    JSONObject jsonBody = new JSONObject();
    jsonBody.put(KEY_USERNAME, username);
    jsonBody.put(KEY_OldPASSWORD, oldpassword);
    jsonBody.put(KEY_UserPassword, newpassword);
    jsonBody.put(KEY_MasterID, master_id);
    jsonBody.put(KEY_Name, Name);
    final String requestBody = jsonBody.toString();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.i("VOLLEY", response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("VOLLEY", error.toString());
        }
    }) {
        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
            try {
                return requestBody == null ? null : requestBody.getBytes("utf-8");
            } catch (UnsupportedEncodingException uee) {
                VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                return null;
            }
        }

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            String responseString = "";
            if (response != null) {
                responseString = String.valueOf(response.statusCode);
                // can get more details such as response.headers
            }
            return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
        }
    };

    requestQueue.add(stringRequest);
} catch (JSONException e) {
    e.printStackTrace();
}

我已经损坏了masterID并仅发送登录的整数,但是在更改密码的情况下,我希望所有masterID都没有损坏。 不是我添加的,那是错误 ,必须通过参数部分发送。

工作代码如下所示

public class SettingFragment extends Fragment implements View.OnClickListener {
    EditText userName, oldPassword, newPassword;
    String Navigation_URL_SettingRequest = "http://192.168.100.5:84/api/usersApi/updateByMasterID";
    String username, oldpassword, newpassword;
    String master_id, Name, access_token;

    Button save, reset;
    public static final String KEY_Name = "NAME";
    public static final String KEY_USERNAME = "UserName";
    public static final String KEY_OldPASSWORD = "oldPassword";
    public static final String KEY_UserPassword = "UserPassword";
    public static final String KEY_MasterID = "MasterID";


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_setting, container, false);
        setHasOptionsMenu(true);

        userName = (EditText) view.findViewById(R.id.setting_username);
        oldPassword = (EditText) view.findViewById(R.id.setting_oldpassword);
        newPassword = (EditText) view.findViewById(R.id.setting_newpassword);
        save = (Button) view.findViewById(R.id.setting_save);
        reset = (Button) view.findViewById(R.id.setting_reset);

        SessionManagement session = new SessionManagement(getContext());
        session.checkLogin();
        access_token = session.getAccesstToken();
        master_id = session.getMasterId1();
        System.out.println(master_id);
        Name = session.getKeyName();

        save.setOnClickListener(this);
        return view;
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Auto-generated method stub
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.dashboard, menu);
    }


    private void makeJsonSettingRequest() throws JSONException {


        username = userName.getText().toString().trim();
        oldpassword = oldPassword.getText().toString().trim();
        newpassword = newPassword.getText().toString().trim();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Navigation_URL_SettingRequest,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.i("VOLLEY", response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                        System.out.println("This is an Error mate");


                    }
                }) {


            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                // headers.put("Authorization", "Bearer " + access_token);
                //  headers.put("Authorization",   access_token);
                //  headers.put("Content-Type", "application/x-www-form-urlencoded");
                //  headers.put("Content-Type", "application/json");


                return headers;
            }

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
                //JSONObject content = new JSONObject();

                try {
                    map.put(KEY_USERNAME, username);
                    map.put(KEY_OldPASSWORD, oldpassword);
                    map.put(KEY_UserPassword, newpassword);
                    map.put(KEY_MasterID, "s" + master_id);
                    map.put(KEY_Name, Name);
                    Log.d("Success", map.put(KEY_USERNAME, username));
                    Toast.makeText(getContext(), "", Toast.LENGTH_SHORT).show();


                } catch (Exception e) {

                    e.printStackTrace();
                }


                //map.put("access_token", accesstoken);
                //  map.put("grant_type", "password");
                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));


        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(stringRequest);


    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // handle item selection
        switch (item.getItemId()) {
            case R.id.action_settings:
                // do s.th.
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }


    @Override
    public void onClick(View v) {
        try {
            makeJsonSettingRequest();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM