【问题标题】:Service methods cannot return void. retrofit服务方法不能返回 void。改造
【发布时间】:2015-11-25 12:06:56
【问题描述】:

这是我在接口中的方法。我正在调用此函数,但应用程序崩溃并出现此异常:

原因:java.lang.IllegalArgumentException:服务方法不能 返回无效。 对于方法 RestInterface.getOtp

//post method to get otp for login
@FormUrlEncoded
@POST("/store_login")
void getOtp(@Header("YOUR_APIKEY") String apikey, @Header("YOUR_VERSION") String appversion,
            @Header("YOUR_VERSION") String confiver, @Field("mobile") String number, Callback<Model> cb);

这是我调用这个函数的代码

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(API_URL)
            .build();

    RestInterface restApi = retrofit.create(RestInterface.class);
    restApi.getOtp("andapikey", "1.0", "1.0", "45545845454", new Callback<Model>() {

        @Override
        public void onResponse(Response<Model> response) {

        }

        @Override
        public void onFailure(Throwable t) {

        }
    });

【问题讨论】:

  • 我已经创建了一个关于改造 2.0 的帖子。如果有人仍然面临这个问题,请检查它..Retrofit 2.0 android

标签: retrofit


【解决方案1】:

Retrofit 1.9 和 2.0 中异步的区别

/* Retrofit 1.9 中的同步 */

public interface APIService {

@POST("/list")
Repo loadRepo();

}

/* Retrofit 1.9 中的异步 */

public interface APIService {

@POST("/list")
void loadRepo(Callback<Repo> cb);

}

但是在 Retrofit 2.0 上,它要简单得多,因为你可以只用一个模式声明

/* Retrofit 2.0 */

public interface APIService {

@POST("/list")
Call<Repo> loadRepo();

}

// Retrofit 2.0 中的同步调用

Call<Repo> call = service.loadRepo();
Repo repo = call.execute();

// Retrofit 2.0 中的异步调用

Call<Repo> call = service.loadRepo();
call.enqueue(new Callback<Repo>() {
@Override
public void onResponse(Response<Repo> response) {

   Log.d("CallBack", " response is " + response);
}

@Override
public void onFailure(Throwable t) {

  Log.d("CallBack", " Throwable is " +t);
}
});

【讨论】:

    【解决方案2】:

    你总是可以这样做的:

    @POST("/endpoint")
    Call<Void> postSomething();
    

    编辑:

    如果你使用的是 RxJava,从 1.1.1 开始你可以使用Completable 类。

    【讨论】:

      【解决方案3】:

      https://github.com/square/retrofit/issues/297

      请通过此链接。

      "所有接口声明都需要返回一个对象,所有交互都将通过该对象发生。该对象的行为将类似于 Future 并且将是成功响应类型的泛型类型 (T)。"

      @GET("/foo")
      Call<Foo> getFoo();
      

      基于新的 Retrofit 2.0.0 beta 你不能将返回类型指定为 void 以使其异步

      根据改造中的代码 (https://github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit/MethodHandler.java),当您尝试使用 2.0.0 beta 的先前实现时,它会显示异常

      if (returnType == void.class) {
      throw Utils.methodError(method, "Service methods cannot return void.");
      }
      

      【讨论】:

        【解决方案4】:

        根据您的课程,您使用的似乎是 Retrofit 2.0.0,该版本目前处于测试阶段。我认为不再允许在您的服务方法中使用 void。相反,返回Call,您可以将其加入队列以异步执行网络调用。

        或者,将您的库放到 Retrofit 1.9.0 并用 RestAdapter 替换您的 Retrofit 类。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-10-03
          • 1970-01-01
          • 2015-04-30
          • 1970-01-01
          • 1970-01-01
          • 2015-12-24
          • 2018-03-23
          • 1970-01-01
          相关资源
          最近更新 更多