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

时间:2017-05-29 10:48:11

标签: android object post android-volley

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

SettingFragment

  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发送但是通过Code我无法做到。

enter image description here

logcat的

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
  

如何解决这个问题?

5 个答案:

答案 0 :(得分:2)

您可以尝试使用此代码,我已经实现了与您相同的操作......它可能适用于您

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


    }

答案 1 :(得分:0)

您还可以使用parametersJSONObject作为StringRequest发送。

试试这个:

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

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

答案 2 :(得分:0)

在后端使用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);
    }
}

}

答案 3 :(得分:0)

你可以试试这个

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

答案 4 :(得分:0)

我已经破坏了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();
        }
    }
}