问题
I just implemented the retrofit android library for rest api call but it is not working and has no error. My code is
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);
}
}
and in activity i call
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) {
}
});
And in AndroidManifest i set the permission for internet.
回答1:
How to make RestClient as a singleton:
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);
}
}
Then when you wanna call api you should always call:
ApiInterface api = RestClient.getInstance();
api.callWhatApiYouWant
回答2:
I am answering late but it will be useful for others, I preferred to use retrofit 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'
Quit Simple to create instance.
public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
Here is Detailed explanation about retrofit 2 android best example and quit simple to understand. http://al-burraq.com/retrofit-android-get-and-post-api-request-tutorial/
来源:https://stackoverflow.com/questions/32389584/retrofit-android-not-working-and-has-no-error