2017-06-05 76 views
0

关于这个问题内容类型不匹配于Android发送JSON请求时Laravel

我想用用写在Laravel的API抽射发送JSON请求,当我要求检查服务器以确保响应应也是JSON类型....它说$request->expectsJson()是错误的。

我做错了什么?

什么是expectsJson在Laravel?:https://laravel.com/api/5.3/Illuminate/Http/Request.html#method_expectsJson

Laravel代码:文件名:应用程序\例外\ 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代码发送请求

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

     } 
    }); 

回答

2

这些是HTTP头,而不是请求身体参数

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

您需要覆盖Volley的Map<String, String> getHeaders()方法。

How to set custom header in Volley Request

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

我还建议建立不同的网址。

Use URI builder in Android or create URL with variables

+0

你可以慷慨地给予覆盖代码吗? – Pankaj

+0

已添加。不确定您的API令牌。它似乎是在URL中,而不是身体 –

+0

只是完美的。感谢分享这么棒的知识。 +1和接受和赏金是美国 – Pankaj