android Retrofit 2 发布到 laravel 不起作用

我正在使用 Retrofit 2,尝试将数据发送到我的 Laravel Web。


InitRetrofit.java


public 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.java


public 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.java


public 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。


江户川乱折腾
浏览 106回答 1
1回答

慕尼黑5688855

更新我终于通过尝试使用 Postman 发布它给出了错误 419 页面已过期,因为它没有 csrf 令牌(因为我将其直接发布到控制器而没有视图可以添加 csrf),所以我添加了异常中间件文件夹中VerifyCsrfToken.php上的url,所以它变成这样class VerifyCsrfToken extends Middleware{&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Indicates whether the XSRF-TOKEN cookie should be set on the response.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @var bool&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; protected $addHttpCookie = true;&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* The URIs that should be excluded from CSRF verification.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @var array&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; protected $except = [&nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; &nbsp; &nbsp; '/lapor/android'&nbsp; &nbsp; ];}也许还有另一种方法可以做到这一点,例如在控制器内生成 csrf 令牌。希望这会对某人有所帮助。
打开App,查看更多内容
随时随地看视频慕课网APP