[英]send json to Laravel using postman and android
我正在嘗試使用郵遞員將 json 發送到 Lavavel,但我遇到了這個錯誤。
在此處輸入圖像描述這是我的 json 代碼:
{
"email":"test@test.com",
"password":"testtest"
}
這是 Laravel 代碼:
Route::get('/r','test@store');
和
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Log;
class test extends Controller
{
public function store(Request $request)
{
$email = $request->input('email');
$password = $request->input('password');
Log::info('test');
Log::info($email);
Log::info($password);
DB::table('login')->insert([
['email' => $email],
['password' => $password]
]);
}
}
我也嘗試使用 android 使用 volley 發送數據,因此檢查了 Laravel 日志:
Column 'email' cannot be null (this is Laravel logs)
並在 android 日志上:
E/Volley:[299] BasicNetwork.performRequest: http : //192.168.1.4 :8000/r 的意外響應代碼 500 D/錯誤:com.android.volley.ServerErro
我的安卓代碼是:
public class ApiService {
private final Context context;
public ApiService(Context context){
this.context=context;
}
public void loginUser(String email, String password, final OnLoginResponse onLoginResponse){
JSONObject requestJsonObject=new JSONObject();
try {
requestJsonObject.put("email",email);
requestJsonObject.put("password",password);
JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, "http://192.168.1.4:8000/r",requestJsonObject , new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("response",response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
}
}) {
@Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
return headers;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(18000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(context).add(request);
} catch (JSONException e) {
Log.e(TAG, "loginUser: "+e.toString());
}
}
public interface OnLoginResponse{
void onResponse(boolean success);
}
}
我希望這可以幫助人們嘗試搜索如何將 JSON 數據發送到 Laravel,不僅針對 Android 應用程序,而且針對所有應用程序。 此解決方案的目標是確定您是否可以向 laravel 發送 JSON 數據。
首先,您必須從https://www.getpostman.com/下載郵遞員以測試您的 API 是否真的有效。
這是控制器部分,它將顯示您發送的 JSON 數據是否被成功接受。
而且,如果您嘗試將 POST 數據發送到 laravel,默認情況下,他們提供了一個 CSRF 令牌,如果您打算使用 laravel 的 MVC,則該令牌適用於表單。 與此同時,我們將把它刪除並注釋掉。 只需轉到 app/http/kernel.php
現在您將從之前的代碼中獲得以下結果
$json = json_decode($request['json']);
echo $json->{'email'};
echo "\n";
echo $json->{'password'};
如果您要發送數據,則需要在郵遞員上使用POST或PUT方法,特別是如果您要發送正文,則意味着您正在發送數據。 Get方法用於從服務檢索數據。 請查看CRUD函數以獲取更多信息。 您的郵遞員應該看起來像這樣
最后在您的Android代碼中嘗試更改此行
JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, "http://192.168.1.4:8000/r",requestJsonObject , new Response.Listener<JSONObject>() {
使用Request.Method.POST
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.