我到处搜索,我看过的教程与Retrofit提供的文档不符。我认为这是一个愚蠢的问题,因为我还没能找到答案。我是Android编程的新手。
我跟随Codepath's guide并且在其所在的部分:
创建Retrofit实例
To send out network requests to an API, we need to use the [Retrofit
builder] class and specify the base URL for the service.
// Trailing slash is needed
public static final String BASE_URL = "http://api.myservice.com/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
我不知道把它放在哪个类中。或者我为它创建一个新类?
答案 0 :(得分:4)
Jonathan为您提供了大量代码,但我认为您的问题更多的是入门级“如何使用它?”问题,对吧?
所以基本上你发布的代码会创建一个Retrofit
实例。它是一个能够创建api接口对象的对象。一个Retrofit
对象处理一个基本URL。
您可以通过创建interface
来定义api端点和预期响应。使用网站上的示例:
端点接口
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
然后,使用您创建的Retrofit实例,您可以通过调用
来实例化此接口的实现GitHubService service = retrofit.create(GitHubService.class);
并通过调用
简单地向api发送请求Call<List<Repo>> repos = service.listRepos("octocat");
repos.enqueue(callback) //add a callback where you can handle the response
Jonathan发布的示例使用RxJava调用适配器,但您现在应该跳过该部分以使自己更容易。
编辑:添加评论中要求的示例。
对于此api端点 - &gt; https://api.textgears.com/check.php?text=I+is+an+engeneer!&key=DEMO_KEY
你需要
@GET("check.php")
Call<YourResponseClass> performCheck(@Query("text") String text, @Query("key") apiKey);
这也是一个有趣的案例,因为您肯定需要为每个请求添加apiKey。但是,每次手动将其作为参数添加并不是一个好习惯。有一个解决方案 - Interceptor
。
public class ApiKeyRequestInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
final HttpUrl newUrl = request.url().newBuilder()
.addQueryParameter(Constants.API.PARAM_API_KEY, BuildConfig.NEWS_API_KEY) //add your api key here
.build();
return chain.proceed(request.newBuilder()
.url(newUrl)
.build());
}
}
告诉Retrofit使用它(构建OkHttpClient
)
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new ApiKeyRequestInterceptor())
.build();
Retrofit = new Retrofit.Builder()
.baseUrl(Constants.API.BASE_URL)
.client(client)
.build();
在这种情况下,您的密钥不需要额外的字段,您可以将方法缩小为
Call<YourResponseClass> performCheck(@Query("text") String text);
答案 1 :(得分:3)
您可以创建一个Controller来处理请求。
public class RequestController {
private final static String BASE_URL_CLUB = "url";
private static RequestApiEndpoints apiServiceAsync;
private static RequestController instance;
private static final int TIMEOUT_MILLIS = 10000;
private static final TimeUnit TIMEOUT_UNIT = TimeUnit.MILLISECONDS;
private Context context;
private RequestController(Context context) {
this.context = context;
RxJavaCallAdapterFactory rxAdapter = RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io());
Retrofit retrofitAsync = new Retrofit.Builder()
.baseUrl(BASE_URL_CLUB)
.client(createDefaultOkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(rxAdapter)
.build();
apiServiceAsync = retrofitAsync.create(RequestApiEndpoints.class);
}
private OkHttpClient createDefaultOkHttpClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
return new OkHttpClient().newBuilder()
.cache(new Cache(context.getCacheDir(), 10 * 1024 * 1024)) // 10 MB
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (Utils.hasInternet(context)) {
request = request.newBuilder().header("Cache-Control", "public, max-age=" + 60).build();
} else {
request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24).build();
}
return chain.proceed(request);
}
})
.connectTimeout(TIMEOUT_MILLIS, TIMEOUT_UNIT)
.readTimeout(TIMEOUT_MILLIS, TIMEOUT_UNIT)
.writeTimeout(TIMEOUT_MILLIS, TIMEOUT_UNIT)
.addInterceptor(interceptor)
.build();
}
public static RequestController getInstance(Context context) {
if (instance == null) {
instance = new RequestController(context);
}
return instance;
}
public Observable<ResponseObject> getExampleInfo(String param) {
return apiServiceAsync.getExampleInfo(param).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}
}
然后你的界面:
public interface RequestApiEndpoints {
@GET("path/to/request") //without the base url
Observable<ResponseObject> getExampleInfo(@Query("param") String param);
}
然后在你的Application类上:
public class MyApplication extends Application {
...
public static RequestController requestController;
...
@Override
public void onCreate() {
super.onCreate();
requestController = RequestController.getInstance(this);
...
}
public static FPDApplication getInstance() {
if (instance == null) {
instance = new FPDApplication();
}
return instance;
}
}
然后访问您的RequestController,只需执行以下操作:
MyApplication.requestController.getExampleInfo(string);