Can't send volley post request from android phone

淺唱寂寞╮ 提交于 2019-12-12 06:29:48

问题


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


来源:https://stackoverflow.com/questions/36915322/cant-send-volley-post-request-from-android-phone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!