在MainActivity.java //我们的网络服务的根网址 public static final String ROOT_URL =" http://pratikbutani.x10.mx&#34 ;; RestAdapter适配器=新的RestAdapter.Builder() .setEndpoint(ROOT_URL) .build();
//Creating an object of our api interface
BooksAPI api = adapter.create(BooksAPI.class);
//Defining the method
api.getBooks(new Callback<List<Contact>>() {
@Override
public void success(List<Contact> list, Response response) {
//Dismissing the loading progressbar
//Storing the data in our list
books = list;
//Calling a method to show the list
showList();
}
@Override
public void failure(RetrofitError error) {
//you can handle the errors here
}
});
public interface BooksAPI {
/*Retrofit get annotation with our URL
And our method that will return us the list ob Book
*/
@GET("/json_data.json")
public void getBooks(Callback<List<Contact>> response);
}
答案 0 :(得分:1)
//改装课程
public class NetworkContext {
private static final String BASE_URL = "https://xyz/";
private Map<String, Object> services;
private Retrofit retrofit;
private static final NetworkContext INSTANCE = new NetworkContext();
private NetworkContext() {
services = new HashMap<>();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
public static NetworkContext getInstance() {
return INSTANCE;
}
public synchronized <T> T getService(Class<T> clazz) {
String key = clazz.getName();
if (services.containsKey(key)) {
return (T) services.get(key);
} else {
T newClass = retrofit.create(clazz);
services.put(key, newClass);
return newClass;
}
}
}
// api interface
public interface APIInterface {
@GET("will be attached with the base url")
Call<Model> getData();
}
//调用
Call call = apiInterface.getData();
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Model model = (Model) response.body();
// here you can retrieve data
}
@Override
public void onFailure(Call call, Throwable t) {
call.cancel();
}
});