0

Spending sleepless nights trying to successfully post this data to my server but it is returning an error, It is just working fine in postman, the problem is it's sending an empty request to the server . Link to server script. Guys please help me resolving the error. This is the screenshot of postman request and response.

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

Below is the console traces on server side:

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

  

Editing further to show my server side code:

Controller

  @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;
    }
Disha Singh
  • 27
  • 1
  • 2
  • 7

2 Answers2

0

Try to send JsonObjectRequest instead of StringRequest. Follow this answer

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());
            }
        });
Atik Faysal
  • 158
  • 1
  • 13
  • I followed your answer but it is still sending an empty request to the server. Many more methods i tried earlier but nothing worked. – Disha Singh Dec 12 '20 at 06:11
  • use Rertrofit library instead of volley, Retrofit is more simple than volley, – Atik Faysal Dec 12 '20 at 06:52
  • did you follow this answer https://stackoverflow.com/questions/28344448/how-to-send-json-object-to-server-using-volley-in-android – Atik Faysal Dec 12 '20 at 06:53
  • I followed the link you shared, retrofit2 is sending an empty request whereas the request on postman is posting with success – Disha Singh Dec 12 '20 at 07:19
0

I have solved my problem it was a problem just added host in the header and the whole problem solved hence saved data in my database.

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

Thanks especially to @ATIK_FAYSAL for your kind efforts.

Disha Singh
  • 27
  • 1
  • 2
  • 7