Android Retrofit无法与Laravel API端点一起使用

时间:2019-01-25 12:04:05

标签: android laravel api retrofit

我一直想弄清楚为什么最终的android改版不发送POST。这是我所做的。在Laravel中,我设置了模型,控制器,将VerifyCsrfToken更改为允许api。然后,我设置路线网络和API。所有内容都通过邮递员进行了测试,并且可以正常工作,但是当我尝试通过android发布代码失败。

这是我对Laravel的狂喜

Web.php

Route::get('/', function () {
return view('welcome');
});

Route::resource('/api/student', 'StudentsApiController');

Api.php

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::post('student/store', 'StudentsApiController@store');

Android-api.java

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface Api {

    @FormUrlEncoded
    @POST("store")
    public Call<ResponseBody> store(
        @Field( "email" ) String email,
        @Field ( "password" ) String password,
        @Field ( "name" ) String name,
        @Field ( "school" ) String school
    );

}

Android-RetrofitClient.java

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public
class RetrofitClient {

    private static final String BASE_URL = "192.168.2.23/api/student/";
    private static RetrofitClient mInstance;
    private Retrofit retrofit;

    private RetrofitClient()
    {
        retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory ( GsonConverterFactory.create () )
            .build ();
    }

    public static synchronized RetrofitClient getmInstance(){
        if(mInstance == null){
            mInstance = new RetrofitClient ();
        }
        return mInstance;
    }

    public Api getApi(){
        return retrofit.create ( Api.class );

    }
}

Android-MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public
class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText editTextEmail, editTextPassword, editTextName, editTextSchool;

    @Override
    protected
    void onCreate ( Bundle savedInstanceState ) {
        super.onCreate ( savedInstanceState );
        setContentView ( R.layout.activity_main );

        editTextEmail = findViewById ( R.id.editTextEmail );
        editTextPassword = findViewById ( R.id.editTextPassword );
        editTextName = findViewById ( R.id.editTextName );
        editTextSchool = findViewById ( R.id.editTextSchool );

        findViewById ( R.id.buttonSignUp ).setOnClickListener ( this );

        findViewById ( R.id.textViewLogin ).setOnClickListener ( this );

    }

    private
    void userSignUp () {
        String email = editTextEmail.getText ( ).toString ( ).trim ( );
        String password = editTextPassword.getText ( ).toString ( ).trim ( );
        String name = editTextName.getText ( ).toString ( ).trim ( );
        String school = editTextSchool.getText ( ).toString ( ).trim ( );

        if (email.isEmpty ( )) {
            editTextEmail.setError ( "Email required" );
            editTextEmail.requestFocus ( );
            return;
        }

        if (Patterns.EMAIL_ADDRESS.matcher ( email ).matches ( )) {
            editTextEmail.setError ( "Email a valid email" );
            editTextEmail.requestFocus ( );
            return;
        }

        if (password.isEmpty ( )) {
            editTextPassword.setError ( "Password is required" );
            editTextPassword.requestFocus ( );
            return;
        }
        if (password.length ( ) < 6) {
            editTextPassword.setError ( "Password should be 6 characters long" );
            editTextPassword.requestFocus ( );
            return;
        }
        if (name.isEmpty ( )) {
            editTextName.setError ( "Name is required" );
            editTextName.requestFocus ( );
            return;
        }
        if (school.isEmpty ( )) {
            editTextSchool.setError ( "Name is required" );
            editTextSchool.requestFocus ( );
            return;
        }


    }

    @Override
    public
    void onClick ( View v ) {
        switch (v.getId ( )) {
            case R.id.buttonSignUp:
                userSignUp ( );
                break;
            case R.id.textViewLogin:
                break;
        }

        Call <ResponseBody> call = RetrofitClient
                .getmInstance ()
                .getApi ()
                .store("email", "password", "name", "school");

        call.enqueue ( new Callback <ResponseBody> ( ) {
            @Override
            public
            void onResponse ( Call <ResponseBody> call, Response<ResponseBody> response ) {
                try {
                    String s = response.body ().string ();
                    Toast.makeText ( MainActivity.this, s, Toast.LENGTH_LONG ).show ();
                } catch (IOException e) {
                    e.printStackTrace ( );
                }



            }

            @Override
            public
            void onFailure ( Call <ResponseBody> call, Throwable t ) {

                Toast.makeText ( MainActivity.this, t.getMessage (), Toast.LENGTH_LONG ).show ();

            }
        } );


    }
}

我还更改了清单文件以包含internet permission。我使用Vysor进行测试。

3 个答案:

答案 0 :(得分:0)

尝试更改此内容

Route::post('student/store', 'StudentsApiController@store');

Route::post('/store', 'StudentsApiController@store');

答案 1 :(得分:0)

您已经提供了

student中的

BASE_URL端点。像这样更改您的BASE_URL

private static final String BASE_URL = "192.168.2.23/api/";

答案 2 :(得分:0)

改造后的基本url将在第一个/之后删除所有内容,因此您的基本url应该仅包含您的ip和android api文件@post('store')中的内容 应该是@post('api/student/store')base_url ="http://192.168.1.6"为例