2017-05-04 56 views
0

我到處搜索過,而且我看到的教程與Retrofit提供的文檔不匹配。我認爲這是一個愚蠢的問題,因爲我一直無法找到答案。我在Android編程方面是全新的。在哪個類中創建Retrofit實例?

我下面Codepath's guide和我在那裏說的部分:

創建改造實例

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(); 

我不知道哪個類中把這個還是我創建一個新的。上課呢?

回答

2

喬納森已經讓你滿意了代碼的代碼,但我認爲你的問題更多是入門級的「我如何使用它?」問題,對吧?

因此,基本上您發佈的代碼會創建Retrofit實例。它是一個能夠創建API接口對象的對象。一個Retrofit對象處理一個基本URL。

通過創建interface s來定義api端點和預期響應。使用實例從網站:

端點接口

public interface GitHubService { 
    @GET("users/{user}/repos") 
    Call<List<Repo>> listRepos(@Path("user") String user); 
} 

然後使用您創建的改造實例,您可以通過調用

GitHubService service = retrofit.create(GitHubService.class); 

和簡單的發送請求實例化這個接口的實現通過撥打電話

Call<List<Repo>> repos = service.listRepos("octocat"); 
repos.enqueue(callback) //add a callback where you can handle the response 

示例pos Jonathan使用RxJava調用適配器,但現在應該略過這部分,以使自己更容易。

編輯:添加評論中請求的示例。

這個API的終點 - >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()); 
} 
} 

,並告訴改造使用它(建立一個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); 
+0

你是對的人,Rx是一整個步驟,但也很好地瞭解它並學習,它更容易處理Rx響應的方式,而不是裸手 –

+0

當然,我在我的所有項目中都使用了Rx,但它仍然是一個單獨的東西,所以讓他一次添加一塊磚塊:) – LukeJanyga

+0

她:)但謝謝你,這個解釋非常有幫助! – Ang

1

您可以創建一個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); 
} 

然後在您的應用程序類:

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); 
+0

謝謝!我想知道如何將此添加到我的代碼中 – Ang