Android 截击向服务器发送状态为 200 的空请求

Android volley posting empty request to server with 200 status

花费不眠之夜试图成功 post 此数据到我的服务器,但它返回错误,它在 postman 中工作正常,问题是它正在发送一个空请求到服务器 。 Link 到服务器脚本。伙计们请帮我解决错误。这是 postman 请求和响应的屏幕截图。

PostmanRequest

PostmanResponse

private void startLogin(final String mobileNumber) {
                /*customLoader.show ();*/
                try {
                    RequestQueue requestQueue = Volley.newRequestQueue (this);
                    String url = "http://192.xxx.xx.xx:8080/xxx/user/loginwithotp";
                    customLoader.show();
                    JSONObject jsonBody = new JSONObject ();
              
                    jsonBody.put ("mobileNumber", mobileNumber);
                    final String requestBody = jsonBody.toString ();
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Log.i("VOLLEY", response);
        
                            Intent home = new Intent (getApplicationContext (), Dash.class);
                            home.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity (home);
                            finish ();
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            customLoader.dismiss();
                            Log.d("error" , error.toString());
                        }
                    }) {
                        /*   @Override
                           public String getBodyContentType() {
                               return "application/json; charset=utf-8";
                           }*/
                        @Override
                        public Map<String, String> getHeaders() throws AuthFailureError {
                            HashMap<String, String> headers = new HashMap<String, String>();
                            headers.put("Content-Type", "application/json; charset=utf-8");
                            headers.put("X-Org-ID", "ajh");
                            return headers;
                        }
        
                        @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
                        protected Response<String> parseNetworkResponse(NetworkResponse response) {
                            String responseString = "";
                            if (response != null) {
                                responseString = String.valueOf (response.statusCode);
                                // can get more details such as response.headers
                            }
                            return Response.success (responseString, HttpHeaderParser.parseCacheHeaders (response));
                        }
                    };
                    stringRequest.setShouldCache(false);
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy (30000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    requestQueue.add (stringRequest);
                } catch (JSONException e) {
                    e.printStackTrace ();
                }
            }
            @Override
            public void onDestroy() {
                super.onDestroy();
                if (customLoader != null) {
                    customLoader.dismiss();
                    customLoader = null;
                }
            }
        }
    
    

下面是服务器端的控制台跟踪:

    [DEBUG] 2020-12-12 07:24:35.422 [http-nio-8080-exec-7] AntPathRequestMatcher - Checking match of request : '/user/loginwithotp'; against '/authenticateUser'
    [DEBUG] 2020-12-12 07:24:35.422 [http-nio-8080-exec-7] AntPathRequestMatcher - Checking match of request : '/user/loginwithotp'; against '/heartbeat'
    [DEBUG] 2020-12-12 07:24:35.422 [http-nio-8080-exec-7] AntPathRequestMatcher - Checking match of request : '/user/loginwithotp'; against '/'
    [DEBUG] 2020-12-12 07:24:35.422 [http-nio-8080-exec-7] AntPathRequestMatcher - Checking match of request : '/user/loginwithotp'; against '/home'
    [DEBUG] 2020-12-12 07:24:35.422 [http-nio-8080-exec-7] AntPathRequestMatcher - Checking match of request : '/user/loginwithotp'; against '/subscribe/**'
    [DEBUG] 2020-12-12 07:24:35.422 [http-nio-8080-exec-7] AntPathRequestMatcher - Checking match of request : '/user/loginwithotp'; against '/getLogo'
    [DEBUG] 2020-12-12 07:24:35.422 [http-nio-8080-exec-7] AntPathRequestMatcher - Checking match of request : '/user/loginwithotp'; against '/user/signup'
    [DEBUG] 2020-12-12 07:24:35.422 [http-nio-8080-exec-7] AntPathRequestMatcher - Checking match of request : '/user/loginwithotp'; against '/checkToken'
    [DEBUG] 2020-12-12 07:24:35.422 [http-nio-8080-exec-7] AntPathRequestMatcher - Checking match of request : '/user/loginwithotp'; against '/user/loginwithotp'
    [DEBUG] 2020-12-12 07:24:35.422 [http-nio-8080-exec-7] FilterChainProxy - /user/loginwithotp has an empty filter list
    [INFO ] 2020-12-12 07:24:35.422 [http-nio-8080-exec-7] MultiReadHttpservletRequest - /xx/xxx/loginwithotp Requesting IP address:  192.168.xx.xxx Content Type:  application/json; charset=utf-8
    [INFO ] 2020-12-12 07:24:35.447 [http-nio-8080-exec-7] MultiReadHttpservletRequest - Payload: {}
    [DEBUG] 2020-12-12 07:24:36.117 [http-nio-8080-exec-7] DispatcherServlet - POST "/dmp/user/loginwithotp", parameters={}
    [DEBUG] 2020-12-12 07:24:38.052 [http-nio-8080-exec-7] RequestMappingHandlerMapping - Mapped to public com.k3i.dmp.vo.AuthenticationVO com.k3i.dmp.controller.UserController.signInWithOTP(com.k3i.dmp.vo.AuthenticationVO)
    [DEBUG] 2020-12-12 07:24:40.996 [http-nio-8080-exec-7] RequestResponseBodyMethodProcessor - Read "application/json;charset=utf-8" to [AuthenticationVO [authToken=null, isFirstLogin=false, isLocked=false, loginRoles=null, userId=null,  (truncated)...]
    login request is:-AuthenticationVO [authToken=null, isFirstLogin=false, isLocked=false, loginRoles=null, userId=null, loginName=null, username=null, message=null, newPassword=null, password=null, isFirstTimeLogin=false, status=false, expiry=null, orgID=null, ipAddress=null, device=null, tokenInfo=null, fromInternalApp=false, noToken=false, organizationName=null, email=null, mobileNumber=813xxxxxxx, providerId=null, otp=null]
    request body is empty
    [DEBUG] 2020-12-12 07:24:42.060 [HikariPool-1 housekeeper] HikariPool - HikariPool-1 - Pool stats (total=10, active=0, idle=10, waiting=0)
    [INFO ] 2020-12-12 07:24:41.499 [http-nio-8080-exec-7] UserController - authenticateUser - before returning
    [DEBUG] 2020-12-12 07:24:42.761 [HikariPool-2 housekeeper] HikariPool - HikariPool-2 - Pool stats (total=10, active=0, idle=10, waiting=0)
    [DEBUG] 2020-12-12 07:24:43.535 [http-nio-8080-exec-7] RequestResponseBodyMethodProcessor - Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, application/*+json]
    [DEBUG] 2020-12-12 07:24:43.536 [http-nio-8080-exec-7] RequestResponseBodyMethodProcessor - Writing [AuthenticationVO [authToken=null, isFirstLogin=false, isLocked=false, loginRoles=null, userId=null,  (truncated)...]

  

进一步编辑以显示我的服务器端代码:

控制器

  @PostMapping(path = ENDPOINT_MOBILE_OTP)
    public AuthenticationVO signInWithOTP(@Valid @RequestBody AuthenticationVO authenticationVO){
        System.out.println("login request is:-"+authenticationVO.toString());
        try {
        if (authenticationVO != null) {
            MultitenantUtility.request = httpRequest;
            String tenantId = multitenantUtility.resolveCurrentTenantIdentifier();
            if (tenantId != null) {
                multitenantUtility.setCurrentTenant(tenantId);
                authenticationVO = userService.checkLoginCredentialsWithOTP(authenticationVO);
            } else {
                System.out.println("request body is empty");
                //throw new DMPBadRequestException("Request body is empty");
            }
            }
        }
        catch(Exception e)
        {
            System.out.println("Excepton "+e);
        }
        finally
        {
            multitenantUtility.clearThreadLocal();
            LOGGER.info("authenticateUser - before returning");
        }
        
        return authenticationVO;
    }

尝试发送 JsonObjectRequest 而不是 StringRequest。

JsonObjectRequest request_json = new JsonObjectRequest(Request.Method.POST,url,object,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.i("info", response.toString());
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.e("Error: ", error.getMessage());
            }
        });

我已经解决了我的问题,这是一个问题,只是在 header 中添加了主机,整个问题都解决了,因此将数据保存在我的数据库中。

       @Override
                            public Map<String, String> getHeaders() throws AuthFailureError {
                                HashMap<String, String> headers = new HashMap<String, String>();
                                headers.put("Content-Type", "application/json; charset=utf-8");
                                headers.put("Host", "localhost:8080");

                        
                                return headers;
                            }

特别感谢@ATIK_FAYSAL的努力。