1

当我在 volley 中使用 JsonObjectRequest 进行 POST 请求调用时,然后在某些 wifi 上它正在发送空体。但它适用于 StringRequest POST 请求。它在所有移动网络上都运行良好。

我正在使用 node.js 服务器和 expressjs/body-parser。当我使用 Postman 发出 POST 请求时,一切正常。

错误是什么?如果有人想查看我可以提供的代码。

使用 StringRequest 的 POST 请求

  private void LoginUser(final String email,final String pass) {

        try {

            /*Map<String, String> params = new HashMap<String, String>();
            params.put("username", email);
            params.put("password", pass);
            JSONObject jsonParams = new JSONObject(params);*/

            final StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {

                            //Toast.makeText(getApplicationContext(),response.toString(),Toast.LENGTH_LONG).show();

                            try
                            {
                                Log.i("Inside try", "yes");
                                JSONObject jsonResponse = new JSONObject(response).getJSONObject("user");
                                Log.i("User name",jsonResponse.getString("name"));
                                Constants.setClinicName(jsonResponse.getString("name"));

                                String TokenDB=new JSONObject(response).getString("token");

                                //Toast.makeText(getApplicationContext(),TokenDB,Toast.LENGTH_LONG).show();


                                if(pd.isShowing())
                                {
                                    pd.dismiss();
                                }



                                //Maintaining LogIn data till user clicks LogOut
                                SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                                SharedPreferences.Editor editor = app_preferences.edit();
                                editor.putString("Token",TokenDB);
                                //editor.putString("username", username);
                                editor.commit();

                                //Printing Token in Log in case of null token debugging
                                /*String status=manager.getPreferences(ClinicLogin.this,"token");
                                Log.d("token", status);
*/
                                Intent intent=new Intent(ClinicLogin.this,MainActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                                startActivity(intent);

                            }catch (JSONException ks)
                            {
                                ks.printStackTrace();
                                Toast.makeText(getApplicationContext(),
                                        "Oops! The Username & Password Do Not Match. Please try again!",
                                        Toast.LENGTH_LONG).show();
                            }

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

                            //   Handle Error
                            if(pd.isShowing()) {pd.dismiss();}
                            if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof AuthFailureError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "User not authorized", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof ServerError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Server error", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof NetworkError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof ParseError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Error consuming request", Toast.LENGTH_SHORT).show();
                            }
                            else error.printStackTrace();

                        }
                    }){
                @Override
                protected Map<String,String> getParams(){
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("username", email);
                    params.put("password", pass);
                    return params;
                }

            };

            RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                    7000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            requestQueue.add(stringRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

使用 JsonobjectRequest 进行 POST 调用

private void LoginUser(String email,String pass) {

        try {

            Map<String, String> params = new HashMap<String, String>();
            params.put("username", email);
            params.put("password", pass);
            JSONObject jsonParams = new JSONObject(params);
            JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, REGISTER_URL, jsonParams,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            try {
                                // Parsing json object response
                                // response will be a json object
                                String TokenDB = response.getString("token");
                                JSONObject user=response.getJSONObject("user");
                                Constants.setClinicName(user.getString("name"));

                                //Constants.setTokenDB(TokenDB);
                                if(pd.isShowing())
                                {
                                    pd.dismiss();
                                }

                                //Maintaining LogIn data till user clicks LogOut
                                SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                                SharedPreferences.Editor editor = app_preferences.edit();
                                editor.putString("Token",TokenDB);
                                //editor.putString("username", username);
                                editor.commit();

                                //Printing Token in Log in case of null token debugging
                                /*String status=manager.getPreferences(ClinicLogin.this,"token");
                                Log.d("token", status);
*/
                                Intent intent=new Intent(ClinicLogin.this,MainActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                                startActivity(intent);
                                }
                            catch (JSONException e)
                            {
                                e.printStackTrace();
                                Toast.makeText(getApplicationContext(),
                                        "Oops! The Username & Password Do Not Match. Please try again!",
                                        Toast.LENGTH_LONG).show();
                              }

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

                            //   Handle Error
                            if(pd.isShowing()) {pd.dismiss();}
                            if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof AuthFailureError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "User not authorized", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof ServerError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Server error", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof NetworkError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof ParseError) {
                                //TODO
                                error.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Error consuming request", Toast.LENGTH_SHORT).show();
                            }
                            else error.printStackTrace();

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

            RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
            postRequest.setRetryPolicy(new DefaultRetryPolicy(
                    7000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            requestQueue.add(postRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
4

1 回答 1

0
package com.example.mwakidoshi;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * Created by Sly on 2017-11-17.
 */

public class CustomRequest extends Request<JSONObject> {
    private Response.Listener<JSONObject> listener;
    private Map<String, String> params;

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

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

    @Override
    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) {
        listener.onResponse(response);
    }
}
于 2017-11-17T10:34:00.853 回答