我正在使用 Retrofit 2,嘗試將數據發送到我的 Laravel Web。InitRetrofit.javapublic class InitRetrofit { public static String API_URL = "http://192.168.1.2/sra-copy/public/"; public static Retrofit setInit(){ return new Retrofit.Builder().baseUrl(API_URL).addConverterFactory(GsonConverterFactory.create()).build(); } public static ApiService getInstance(){ return setInit().create(ApiService.class); }}ApiService.javapublic interface ApiService { @FormUrlEncoded @POST("lapor/android") Call<ResponseLapor> input(@Field("lat") String lat, @Field("lng") String lng, @Field("jenis") String jns, @Field("keterangan") String ket);}響應類 ResponseLapor.javapublic class ResponseLapor { @SerializedName("message") @Expose private String message; public String getMessage() { return message; } public void setMessage(String message){ this.message = message; }}呼叫改造public void lapor(){ lat = etLat.getText().toString(); lng = etLng.getText().toString(); keterangan = etKet.getText().toString(); jns = "Ringan"; ApiService api = InitRetrofit.getInstance(); retrofit2.Call<ResponseLapor> call = api.input(lat, lng, jns, keterangan); call.enqueue(new Callback<ResponseLapor>() { @Override public void onResponse(retrofit2.Call<ResponseLapor> call, Response<ResponseLapor> response) { String message = response.body().getMessage(); Toast.makeText(Lapor.this, message, Toast.LENGTH_SHORT).show(); } @Override public void onFailure(retrofit2.Call<ResponseLapor> call, Throwable t) { Toast.makeText(Lapor.this, "Jaringan Error! "+t.getMessage(), Toast.LENGTH_SHORT).show(); } });}路線Route::post('lapor/android', 'AndroidController@Lapor')->name('android.lapor');我認為該錯誤與 URL 有關,因為我有另一個使用相同結構的 android 項目,并且它成功地將數據插入本地主機(不是 laravel),只是本機 PHP。
1 回答

慕尼黑5688855
TA貢獻1848條經驗 獲得超2個贊
更新
我終于通過嘗試使用 Postman 發布它給出了錯誤 419 頁面已過期,因為它沒有 csrf 令牌(因為我將其直接發布到控制器而沒有視圖可以添加 csrf),所以我添加了
異常中間件文件夾中VerifyCsrfToken.php上的url,所以它變成這樣
class VerifyCsrfToken extends Middleware
{
/**
* Indicates whether the XSRF-TOKEN cookie should be set on the response.
*
* @var bool
*/
protected $addHttpCookie = true;
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
'/lapor/android'
];
}
也許還有另一種方法可以做到這一點,例如在控制器內生成 csrf 令牌。
希望這會對某人有所幫助。
- 1 回答
- 0 關注
- 132 瀏覽
添加回答
舉報
0/150
提交
取消