无法从Android手机发送凌空发布请求 [英] Can't send volley post request from android phone

查看:91
本文介绍了无法从Android手机发送凌空发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Volley将带有参数的http发布请求从我的android应用发送到运行在 http://192.168.1.4:3000/battery_signal_report 我很确定服务器运行正常(我已经与Postman成功地对其进行了检查).

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

而且,我使用ip 10.0.2.2通过Android Studio的仿真器成功发送了请求

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

尝试使其工作,我使用了各种请求实现,包括JsonObjectRequest,StringRequest和此处描述的自定义请求:

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

此外,我在某处读到Volley post请求在请求标头方面存在一些问题,因此我尝试以不同的方式覆盖它.

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.

没有任何效果.每次使用空的VolleyError输入调用onErrorResponse.

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

我对android开发还很陌生,所以任何见解都将不胜感激.

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

谢谢.

推荐答案

对于遇到此问题的任何其他人,您都需要忘记标题重写,并设置自己的getBodyContentType()和getBody()方法.遵循这种模式:

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

这篇关于无法从Android手机发送凌空发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆