为了账号安全,请及时绑定邮箱和手机立即绑定

android Retrofit 2 发布到 laravel 不起作用

android Retrofit 2 发布到 laravel 不起作用

PHP
江户川乱折腾 2023-07-15 15:47:09
我正在使用 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 令牌。

希望这会对某人有所帮助。


查看完整回答
反对 回复 2023-07-15
  • 1 回答
  • 0 关注
  • 74 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信