【问题标题】:Retrofit- Android : Request method not acceptedRetrofit-Android:不接受请求方法
【发布时间】:2016-09-07 10:02:17
【问题描述】:

在我的 android 应用程序中,我正在尝试使用改造来进行 api 调用。我想使用改造来执行用户注册。问题是,执行了 api 调用并且调试器也转到了onResponse(),但我的 api 返回响应消息为“不接受请求方法”。我咨询了邮递员,它工作正常。在邮递员中,我将值作为表单数据传递。请帮我解决这个问题。这是我的代码:

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
    );
}

活动

     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");
                    }
                });

注册Pojo

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'
}

请告诉我哪里出错了。

【问题讨论】:

  • 把设备日志放在这里
  • 你的 api 可能只接受 GET 方法。
  • 不,它接受 POST 方法。我在邮递员中使用 POST 方法执行了相同的 api。它与它完美配合。
  • 从@POST("Register.php")中删除.php
  • 并像这样使用@POST("/Register") ......并且还编辑你的logcat错误问题......

标签: android retrofit retrofit2 okhttp3 android-webservice


【解决方案1】:

onResponse() 中,最好检查查询执行是否成功,然后从Response 对象的主体中获取消息。

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");
    }
});

如果isSuccess() 为假,则可以这样获取错误消息:

response.errorBody().string()

如果响应成功,但您无法获取数据,则问题出在您的 RegisterPojo 模型上。您使用的转换库无法将 JSON 转换为对象。还要确保你在这个模型中实现了Serializable

检查此link 并验证RegisterPojo 的格式是否正确。

对我来说,像这样初始化 Retrofit 是可行的:

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();

【讨论】:

  • 我检查了,它进入了response.isSuccess()。这意味着api调用成功。
  • @zanky 查看我的更新答案。还要确保RegisterPojo 格式正确。
  • 我在我的问题中添加了RegisterPojo
  • 尝试添加 Serializable 例如:public class RegisterPojo implements Serializable
【解决方案2】:

你必须将接口声明为Call&lt;RegisterPojo&gt; insertUser(@Body UserClass user); 如果您可以从日志拦截器检查您的请求,您将看到您的请求正文;

用户名:姓名,电子邮件:email@m.com ...

但应该是这样的;

{ “用户名”:姓名,“电子邮件”:email@m.com ... }

idk 为什么,但我提出了我的要求(包括正文和班级)。我确信有一种方法可以使它与字段一起使用,但我找不到。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-18
    • 2016-12-26
    • 1970-01-01
    • 2014-03-27
    • 2020-11-25
    • 2020-04-12
    • 2017-01-30
    • 1970-01-01
    相关资源
    最近更新 更多