带有标头和原始json主体的Volley POST请求

时间:2019-08-28 19:22:03

标签: android authentication post android-volley postman

我正在尝试通过Android App发出发布请求,该请求在请求正文中使用用户名和密码,并在标题中使用内容类型application / json。

我尝试更改内容类型以及如何在正文中发送用户名密码,但仍然没有运气

public class MainActivity extends AppCompatActivity {

    private Button Login;
    private EditText loginEmail, loginPassword;

    String URL = "https://localhost:8080/api/v1/auth";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        loginEmail = (EditText)findViewById(R.id.etUsername);
        loginPassword = (EditText)findViewById(R.id.etPassword);
        Login = (Button)findViewById(R.id.btnLogin);

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("username", loginEmail.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            jsonObject.put("password", loginPassword.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        final String requestBody = jsonObject.toString();


        Login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
                        startActivity(new Intent(MainActivity.this, LandingPage.class));
                        finish();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
                        NetworkResponse response = error.networkResponse;
                        if (error instanceof ServerError && response != null) {
                            try {
                                String res = new String(response.data,
                                        HttpHeaderParser.parseCharset(response.headers, "utf-8"));
                                // Now you can use any deserializer to make sense of data
                                JSONObject obj = new JSONObject(res);
                                Toast.makeText(MainActivity.this, res, Toast.LENGTH_LONG).show();
                                Log.i("MainActivity", res);
                                //use this json as you want
                            } catch (UnsupportedEncodingException e1) {
                                // Couldn't properly decode data to string
                                e1.printStackTrace();
                            } catch (JSONException e2) {
                                // returned data is not JSONObject?
                                e2.printStackTrace();
                            }
                        }
                    }
                })

                {
                    @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
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        Map<String, String> params = new HashMap<String, String>();
                            params.put("Content-Type", "application/json");

                        return params;
                    }

                };
                RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this);
                rQueue.add(request);
            }
        });
    }
}


Postman发出的Post Request效果很好,但是Volley抛出Error 400。 以下是我在控制台中遇到的错误 “ errorSummary”:“请求错误。接受和/或Content-Type标头可能与支持的值不匹配。”

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试使用自定义请求并扩展Request<JSONObject>

CustomRequest类:

public class CustomRequest extends Request<JSONObject> {
    private final Map<String, String> mHeaders;
    private final JSONObject mBody;
    private final Response.Listener<JSONObject> mResponseListener;

    public CustomRequest(int method, String url, Map<String, String> headers, JSONObject body, Response.Listener<JSONObject> responseListener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        this.mHeaders = headers;
        this.mBody = body;
        this.mResponseListener = responseListener;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return mHeaders != null ? mHeaders : super.getHeaders();
    }

    @Override
    public String getBodyContentType() {
        return "application/json; charset=UTF-8";
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        return mBody != null ? mBody.toString().getBytes(Charset.forName("UTF-8")) : super.getBody();
    }

    @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 | JSONException e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        mResponseListener.onResponse(response);
    }
}

用法:

String url = "https://localhost:8080/api/v1/auth";


Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");

JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("username", loginEmail.getText().toString());
    jsonObject.put("password", loginPassword.getText().toString());
} catch (JSONException e) {
        e.printStackTrace();
}

CustomRequest customRequest = new CustomRequest(Request.Method.POST, url, headers, jsonObject, response -> {
    // put your reponse listener code here
}, error -> {
    // put your error listener code here
});

RequestQueue queue = Volley.newRequestQueue(context);
queue.add(customRequest);