Zankhna
Zankhna

Reputation: 4563

Retrofit- Android : Request method not accepted

In my android application, i am trying to use retrofit to make api calls. I want to perform user registration using retrofit. The problem is that, api call is executed and debugger also goes to onResponse(), but my api returns response message as 'Request method not accepted'. I checked with postman, it works properly. in postman, i am passing values as form-data. please help me to solve this issue. here is my code :

public interface RegisterAPI {
    @FormUrlEncoded
    @POST("Register.php")
    Call<RegisterPojo> insertUser(
            @Field("username") String username,
            @Field("email") String email,
            @Field("password") String password,
            @Field("c_password") String c_password
    );
}

Activity

     Retrofit retrofit = new Retrofit.Builder()
                            .baseUrl(BASE_URL)
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();

          RegisterAPI service = retrofit.create(RegisterAPI.class);


          Call<RegisterPojo> call = service.insertUser(
                            edtUname.getText().toString(), edtEmail.getText().toString(),
                            edtPassword.getText().toString(), edtConfirmPassword.getText().toString());

     call.enqueue(new Callback<RegisterPojo>() {
                    @Override
                    public void onResponse(Call<RegisterPojo> call, Response<RegisterPojo> response) {
                        if (response.body() != null) {
//HERE IT SHOWS "Request method not accepted"
                            Log.e("msg", response.body().getMsg());
                            Toast.makeText(mContext, response.body().getMsg(), Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<RegisterPojo> call, Throwable t) {
                        Log.e("msg", "Failed");
                    }
                });

RegisterPojo

public class RegisterPojo {

    @SerializedName("status")
    @Expose
    private Integer status;

    @SerializedName("msg")
    @Expose
    private String msg;

    @SerializedName("id")
    @Expose
    private String id;

    @SerializedName("email")
    @Expose
    private String email;

    @SerializedName("username")
    @Expose
    private String username;

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.2"
    defaultConfig {
        applicationId "app.sample"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.0'
    testCompile 'junit:junit:4.12'
    compile 'com.github.aakira:expandable-layout:1.5.1@aar'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    //    compile 'com.squareup.retrofit2:converter-scalars:2.1.0'
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
    compile 'com.google.code.gson:gson:2.7'
}

please tell me where i am going wrong.

Upvotes: 0

Views: 2463

Answers (2)

Murat
Murat

Reputation: 445

you have to declare interface as Call<RegisterPojo> insertUser(@Body UserClass user); if you can check your request from logging interceptor you will see your request body as;

username: name, email: [email protected] ...

but it should be as;

{ "username": name, "email": [email protected] ... }

idk why but i made work my request as this(with body and class). i am sure there is a way to make to make it work with field but i could not found.

Upvotes: 1

Faraz
Faraz

Reputation: 2154

In onResponse(), its better to check successful query execution and then get the message from the body of Response object.

call.enqueue(new Callback<RegisterPojo>() {
    @Override
    public void onResponse(Call<RegisterPojo> call, Response<RegisterPojo> response){
        if(response.isSuccess())
        {
            // Now try to get message from the body
        }
        else
        {
            // Error occurred while execution
        }
    }

    @Override
    public void onFailure(Call<RegisterPojo> call, Throwable t) {
        Log.e("msg", "Failed");
    }
});

If isSuccess() is false, then the error message can be fetched like this:

response.errorBody().string()

And if response is success, and you cannot get the data then the problem is with your RegisterPojo model. The conversion library which you are using cannot convert JSON to object. Also make sure, you are implementing Serializable in this model.

Check this link and verify RegisterPojo is in correct format or not.

For me, initializing Retrofit like this worked:

private static Gson gson = new GsonBuilder()
    .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
    .serializeNulls()
    .create();

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(GsonConverterFactory.create(gson))
    .build();

Upvotes: 1

Related Questions