onResponse返回变量或抛出异常Retrofit 2.0

时间:2017-06-15 18:42:14

标签: java php retrofit2

我的代码存在问题。

我想返回变量或异常,但我不理解Stack Overflow中不同帖子中的方法。

如果有人可以向我解释一个解决方案,那我就是改造的新手。这是一个项目。

我在类User中使用此实例方法,它是我在MVC中的模型。

我想在创建用户时返回一个布尔变量,如果连接断开则返回异常。

public void connectPassword(String nameuser, String password) {
  Api api = new Api();
  Call < Connection > call = api.getService().connectPassWord(nameuser, password);
  call.enqueue(new Callback < Connection > () {
    public void onResponse(Call < Connection > call, Response < Connection > response) {
      System.out.println(response.body().getToken());
      System.out.println("Connecter");
      User.this.token = response.body().getToken();
      //return boolean her 
    }

    public void onFailure(Call < Connection > call, Throwable throwable) {
      System.out.print(throwable.getMessage());
      // throw Exception her
    }
  });
}


My class ApiService

public interface ApiService {

  @FormUrlEncoded
  @POST("createuser.php")
  Call < Register > sendRegister(@Field("username") String username, @Field("password") String password, @Field("email") String email);

  @FormUrlEncoded
  @POST("login.php")
  Call < Connection > connectPassWord(@Field("username") String username, @Field("password") String password);

  @FormUrlEncoded
  @POST("login.php")
  Call < Connection > connectToken(@Field("username") String username, @Field("token") String password);

}

我的班级Api

public class Api {

  private Retrofit retrofit;
  private ApiService service;

  public Api() {
    this.retrofit = new Retrofit.Builder().baseUrl("http://localhost/ProjetS2/").addConverterFactory(new NullOnEmptyConverterFactory()).addConverterFactory(GsonConverterFactory.create()).build();
    this.service = retrofit.create(ApiService.class);
  }

  public ApiService getService() {
    return this.service;
  }

}

2 个答案:

答案 0 :(得分:1)

这样做

public void connectPassword(String nameuser, String password, MyInterface myInterface) {
    Api api = new Api();
    Call<Connection> call = api.getService().connectPassWord(nameuser, password);
    call.enqueue(new Callback<Connection>() {
        public void onResponse(Call<Connection> call, Response<Connection> response) {
            System.out.println(response.body().getToken());
            System.out.println("Connecter");
            User.this.token = response.body().getToken();
            myInterface.onSuccess(true);
            //return boolean her 
        }

        public void onFailure(Call<Connection> call, Throwable throwable) {
            System.out.print(throwable.getMessage());
            myInterface.onException(throwable.getMessage());
            // throw Exception her
        }
    });
}

<强> MyInterface.class

public interface MyInterface{
public void onSuccess(boolean value);
public void onException(String value);
}

来自您的通话类假设主

public class Main implements MyInterface{

@Override
public void onSuccess(boolean value){
//TODO do your stuff with returned boolean from your call
}

@Override
public void onException(String value){
//TODO you will receive the message here
}

//in your onCreate
...
//method call
connectPassword("username","password",this);

}

希望这有帮助。

答案 1 :(得分:0)

我担心你不能简单地从改装回调中回来。它们是异步的,因此您也可以异步获取值。

然而,您可以做的是使用您自己的回调传播该值。这将导致所谓的“回调地狱”,但是它有效,如果你不太喜欢它,它会没事的。

因此,让我试着引导您完成一个可能的解决方案(有几种方法可以做到这一点)。

假设您的回调定义如下:

public interface UserCallbacks {
   void onUserCreatedSuccessfully(@NonNull User user);

   void onError(@NonNull Throwable throwable);
}

非常简单的界面,公开了两种可以调用的方法。第一个告诉监听器用户已成功创建,另一个告诉监听器有错误。

现在您将方法更改为以下内容:

public void connectPassword(String nameuser, String password, UserCallbacks callbacks) {
   Api api = new Api();
   Call<Connection> call = api.getService().connectPassWord(nameuser, password);
   call.enqueue(new Callback<Connection>() {
    public void onResponse(Call<Connection> call, Response<Connection> response) {
        callbacks.onUserCreatedSuccessfully(/*send the user here*/);
    }

    public void onFailure(Call<Connection> call, Throwable throwable) {
        callbacks.onError(throwable);
    }
   });
}

最后一步是传递回调对象。假设您的控制器实现了回调接口,您可以这样做:

public class UserController implements UserCallbacks {
  // ...
  public void onUserCreatedSuccessfully(@NonNull User user) {
     // do whatever we need to do
  }

  public void onError(@NonNull Throwable throwable) {
     // inspect the error and see what we have to change in the ui
  }

  public void connect(String username, String password) {
     // Suppose you have your service created
     service.connectPassword(username, password. this);
  }
}

确保在UI线程中运行任何UI代码。可以使用runOnUiThread