Can't send volley post request from android ph

2019-09-10 06:45发布

问题:

I'm using Volley to send an http post request with parameters from my android app to my local server running in http://192.168.1.4:3000/battery_signal_report I'm pretty sure the server is running properly (I checked it with Postman successfully).

also, I successfully sent the request through Android Studio's Emulator using ip 10.0.2.2

Trying to make it work, i used various request implementations including JsonObjectRequest, StringRequest and the custom request described here: Volley JsonObjectRequest Post request not working

Also, I've read somewhere that Volley post requests have some problems with the request header, so i tried to override it in different ways.

Nothing works. onErrorResponse is called every time with an empty VolleyError input.

I've fairly new to android development, so any insights would be much appreciated.

Thanks in advance.

回答1:

For anyone else coming across this, you need to forget about the header override and setup your own getBodyContentType() and getBody() methods. Follow this pattern:

StringRequest stringRequest = new StringRequest(Request.Method.POST, url, successListener, errorListener) {
        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";//set here instead
        }

        @Override
        public byte[] getBody() {
            try {
                Map<String, String> params = yourObject.getMappedParams();
                JSONObject json = new JSONObject(params);
                String requestBody = json.toString();
                return requestBody == null ? null : requestBody.getBytes("utf-8");
            } catch (UnsupportedEncodingException uee) {
                return null;
            }
        }
    };