首页 文章

无法从Android手机发送截击请求

提问于
浏览
0

我正在使用Volley从我的Android应用程序发送带有参数的http post请求到我在_1393743中运行的本地服务器 . 我很确定服务器运行正常(我用Postman成功检查了它) .

另外,我使用ip 10.0.2.2通过Android Studio的模拟器成功发送了请求

为了使它工作,我使用了各种请求实现,包括JsonObjectRequest,StringRequest和这里描述的自定义请求:Volley JsonObjectRequest Post request not working

另外,我已经读过Volley帖子请求在请求 Headers 上有一些问题的地方,所以我试图以不同的方式覆盖它 .

什么都行不通 . 每次使用空的VolleyError输入调用onErrorResponse .

我对Android开发很新,所以任何见解都会非常感激 .

提前致谢 .

1 回答

  • 0

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

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

相关问题