改造android不工作,没有错误

时间:2015-09-04 03:25:41

标签: java android rest retrofit

我刚刚为rest api调用实现了改进的android库,但它没有工作且没有错误。我的代码是

ApiInterface.java

public interface ApiInterface {
    @POST("url")
    void getLoginResponse(@Field("username") String username , @Field("password") String password,
                          @Field("clientId") String clientId , Callback<LoginResponse> cb);
}

RestClient.java

public class RestClient {

    private static ApiInterface REST_CLIENT;
    private static String BASE_URL = "base_url";
    static {
        setupRestClient();
    }

    private RestClient() {}

    public static ApiInterface get() {
        return REST_CLIENT;
    }

    private static void setupRestClient() {
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(BASE_URL)
                .build();
        REST_CLIENT = restAdapter.create(ApiInterface.class);
    }
}

在活动中我打电话

RestClient.get().getLoginResponse(usernameText, passwordText, clientId, new Callback<LoginResponse>() {
                        @Override
                        public void success(LoginResponse loginResponse, Response response) {
                            Toast.makeText(getApplicationContext(), loginResponse.getToken(), Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void failure(RetrofitError error) {

                        }
                    });

在AndroidManifest中我设置了互联网权限。

2 个答案:

答案 0 :(得分:0)

如何将RestClient作为单例:

public class RestClient {

    private static ApiInterface REST_CLIENT;
    private static String BASE_URL = "base_url";

    public RestClient() {}

    public static ApiInterface getInstance() {

       //if REST_CLIENT is null then set-up again. 
        if (REST_CLIENT == null) {
           setupRestClient();
        }
        return REST_CLIENT;
   }

    private static void setupRestClient() {
        RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(BASE_URL)
            .build();
        REST_CLIENT = restAdapter.create(ApiInterface.class);
    }
}

然后当你想打电话给api时,你应该总是打电话:

ApiInterface api = RestClient.getInstance();
api.callWhatApiYouWant

答案 1 :(得分:0)

我回答迟到但对其他人有用,我更倾向于使用改装2。

// Retrofit
compile 'com.squareup.retrofit2:retrofit:2.1.0'
// JSON Parsing
compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

退出简单以创建实例。

public static Retrofit getClient(String baseUrl) {
   if (retrofit==null) {
     retrofit = new Retrofit.Builder()
    .baseUrl(baseUrl)
    .addConverterFactory(GsonConverterFactory.create())
    .build();
  }
 return retrofit;
}

以下是关于改造2 android最佳示例和退出简单易懂的详细说明。 http://al-burraq.com/retrofit-android-get-and-post-api-request-tutorial/