0

About the problem

I am trying to send JSON request using Volley using an api written in Laravel and when I request check on server to make sure that the response should also be of type JSON....it says $request->expectsJson() is false.

Am I doing anything wrong?

What is expectsJson in Laravel?: https://laravel.com/api/5.3/Illuminate/Http/Request.html#method_expectsJson

Laravel Code: File Name: app\Exceptions\Handler.php

protected function unauthenticated($request, AuthenticationException $exception)
{
    \Log::info($request->headers->get('Content-Type'));
    if ($request->expectsJson()) {
        return response()->json(['Message' => trans("auth.failed")], 401);
    }

    return redirect()->guest(route('LoginForm'));
}

Android Studio Code sending request using Volley

String Token = Common.getSharedPreference(currentContext, "TokenData");
Map<String, Object> jsonParams = new HashMap<>();
jsonParams.put("api_token", "1" + Token);
jsonParams.put("Content-Type", "application/json; charset=utf-8");
jsonParams.put("Accept", "application/json");

String Url = Common.URL + Common.prefixURL + viewProfileURL + "?api_token=" + Token;

JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, Url,
                                                               new JSONObject(jsonParams),
    new Response.Listener<JSONObject>()
    {
        @Override
        public void onResponse(JSONObject response)
        {

            listener.getResult(null);
        }
    },
    new Response.ErrorListener()
    {
        @Override
        public void onErrorResponse(VolleyError error)
        {

        }
    });
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Pankaj
  • 9,749
  • 32
  • 139
  • 283

1 Answers1

2

These are HTTP Headers, not Request body parameters

jsonParams.put("Content-Type", "application/json; charset=utf-8");
jsonParams.put("Accept", "application/json");

You need to override Volley's Map<String, String> getHeaders() method.

How to set custom header in Volley Request

..., 
    new Response.ErrorListener()
    {
       ... 
    }) { 
       @Override
       public Map<String, String> getHeaders() {
           // Create your Map here
       };
    };

I would also suggest building your URL differently.

Use URI builder in Android or create URL with variables

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245