下面列出了怎么用retrofit2.converter.gson.GsonConverterFactory的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public synchronized T create(@NonNull Builder<T> builder) {
Context ctx = builder.context;
if (!(ctx instanceof Application)) {
ctx = ctx.getApplicationContext();
}
final File cacheDir = new File(ctx.getCacheDir().getAbsolutePath(), ctx.getPackageName());
final Cache cache = new Cache(cacheDir, 10 * 1024 * 1024);
OkHttpClient.Builder http = new OkHttpClient.Builder()
.cache(cache)
.writeTimeout(builder.timeout, TimeUnit.SECONDS);
for (Interceptor interceptor : builder.interceptors) {
http.addInterceptor(interceptor);
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(builder.endpoint)
.client(http.build())
.addConverterFactory(GsonConverterFactory.create(builder.gson))
.build();
return retrofit.create(builder.cls);
}
public void addDownloadInfo(DownloadInfo info) {
info.setState(DownloadInfo.DOWNLOAD);
if (info == null || subscriberMap.get(info.getUrl()) != null) {
subscriberMap.get(info.getUrl()).setDownloadInfo(info);
return;
}
DownloadSubscriber subscriber = new DownloadSubscriber(info);
subscriberMap.put(info.getUrl(), subscriber);
CommonRequest commonRequest;
if (!downloadInfos.contains(info)) {
DownloadInterceptor interceptor = DownloadInterceptor.create(info, subscriber);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(60, TimeUnit.SECONDS);
builder.addInterceptor(interceptor);
Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
.client(builder.build())
.baseUrl(HttpManager.getBaseUrl())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create());
commonRequest = retrofitBuilder.build().create(CommonRequest.class);
info.setRequest(commonRequest);
downloadInfos.add(info);
}
}
public static Retrofit getRetrofitInstance() throws IllegalArgumentException {
if (retrofit == null) {
final String url = getUrl();
if (emptyString(url)) {
UserError.Log.d(TAG, "Empty url - cannot create instance");
return null;
}
final HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
if (D) {
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
}
final OkHttpClient client = enableTls12OnPreLollipop(new OkHttpClient.Builder())
.addInterceptor(httpLoggingInterceptor)
.addInterceptor(new InfoInterceptor(TAG))
.addInterceptor(new GzipRequestInterceptor())
.build();
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(url)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
private static Retrofit buildRetrofit(String baseUrl) {
OkHttpClient.Builder builder = getLogClient();
try {
builder.addInterceptor(chain ->
chain.proceed(addHeader(chain.request().newBuilder()).build()));
if (!baseUrl.equals(ACCOUNT_BASE_URL)) {
builder.addInterceptor(new TokenInterceptor());
}
} catch (Exception e) {
e.printStackTrace();
}
if (Shaft.sSettings.isAutoFuckChina()) {
builder.sslSocketFactory(new RubySSLSocketFactory(), new pixivOkHttpClient());
//builder.dns(new CloudFlareDns(CloudFlareDNSService.Companion.invoke()));
builder.dns(HttpDns.getInstance());
}
OkHttpClient client = builder.build();
Gson gson = new GsonBuilder().setLenient().create();
return new Retrofit.Builder()
.client(client)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(baseUrl)
.build();
}
private void initAPIClient() {
OkHttpClient.Builder okBuilder = MyOkHttpBuilder.getOkHttpBuilder(context);
// okBuilder.retryOnConnectionFailure(true);
// okBuilder.followRedirects(false);
OkHttpClient httpClient = okBuilder.connectTimeout(HTTP_TIMEOUT, timeUnit)
.writeTimeout(HTTP_TIMEOUT, timeUnit)
.readTimeout(HTTP_TIMEOUT, timeUnit)
.build();
Retrofit.Builder builder = new Retrofit.Builder();
retrofit = builder
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(API_BASE_URL)
.client(httpClient)
.build();
mApiService = retrofit.create(ApiService.class);
}
public NetTestDataManager() {
// 这些配置可以放在App工程的网络模块中,这里简要处理就不写了
HttpInfoCatchInterceptor infoCatchInterceptor = new HttpInfoCatchInterceptor();
infoCatchInterceptor.setCatchEnabled(true);
infoCatchInterceptor.setHttpInfoCatchListener(new HttpInfoCatchListener() {
@Override
public void onInfoCaught(HttpInfoEntity entity) {
entity.logOut();
//do something......
}
});
OkHttpClient.Builder okBuilder = new OkHttpClient.Builder();
// okBuilder.cookieJar(RetrofitManager.());
okBuilder.addInterceptor(infoCatchInterceptor);
RetrofitManager.configTrustAll(okBuilder);
Retrofit.Builder builder = new Retrofit.Builder();
builder.baseUrl("http://www.weather.com.cn/")
.client(okBuilder.build())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create());
clientApi = builder.build().create(ClientApi.class);
}
public ApiClient() {
mRetrofitBuilder = new Retrofit.Builder()
.baseUrl("https://api-m.mtime.cn/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create());
mOkHttpClientBuilder = new OkHttpClient.Builder();
mOkHttpClientBuilder.connectTimeout(15, TimeUnit.SECONDS);
if (BuildConfig.DEBUG) {
mOkHttpClientBuilder.addNetworkInterceptor(
new LoggingInterceptor.Builder()
.loggable(BuildConfig.DEBUG)
.setLevel(Level.BODY)
.log(Platform.INFO)
.request("Request")
.response("Response")
.build()
);
}
}
public static SampleService getSampleService() {
if (service == null) {
synchronized (RetrofitHelper.class) {
if (service == null) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://gank.io/")
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
service = retrofit.create(SampleService.class);
}
}
}
return service;
}
/**
* Initialize slack web api client.
*
* @return {@link SlackWebClient}
*/
@Bean
public SlackWebClient getWebClient() {
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(slackTimeout, SECONDS)
.connectTimeout(slackTimeout, SECONDS)
.retryOnConnectionFailure(true)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(slackUrl)
.client(client)
.addConverterFactory(GsonConverterFactory.create(SlackWebClient.gson))
.build();
return retrofit.create(SlackWebClient.class);
}
private ForecastClient(ForecastConfiguration forecastConfiguration) {
Retrofit retrofit = new Retrofit.Builder().baseUrl(Constants.API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create(createGson()))
.client(createOkHttpClient(forecastConfiguration))
.build();
mApiKey = forecastConfiguration.getApiKey();
mLanguage = forecastConfiguration.getDefaultLanguage();
mUnit = forecastConfiguration.getDefaultUnit();
if (forecastConfiguration.getDefaultExcludeList() != null) {
mExcludeBlocks = new ArrayList<>(forecastConfiguration.getDefaultExcludeList());
}
CacheControl cacheControl =
new CacheControl.Builder().maxAge(forecastConfiguration.getCacheMaxAge(), TimeUnit.SECONDS)
.build();
mCacheControl = cacheControl.toString();
mService = retrofit.create(ForecastService.class);
}
@Override
protected List<Review> doInBackground(Long... params) {
// If there's no movie id, there's nothing to look up.
if (params.length == 0) {
return null;
}
long movieId = params[0];
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://api.themoviedb.org/")
.addConverterFactory(GsonConverterFactory.create())
.build();
MovieDatabaseService service = retrofit.create(MovieDatabaseService.class);
Call<Reviews> call = service.findReviewsById(movieId,
BuildConfig.THE_MOVIE_DATABASE_API_KEY);
try {
Response<Reviews> response = call.execute();
Reviews reviews = response.body();
return reviews.getReviews();
} catch (IOException e) {
Log.e(LOG_TAG, "A problem occurred talking to the movie db ", e);
}
return null;
}
/**
* 提供 {@link Retrofit}
*
* @param builder
* @param client
* @param httpUrl
* @return
* @author: jess
* @date 8/30/16 1:15 PM
*/
@Singleton
@Provides
Retrofit provideRetrofit(Application application, @Nullable RetrofitConfiguration configuration, Retrofit.Builder builder, OkHttpClient client
, HttpUrl httpUrl, Gson gson) {
builder
.baseUrl(httpUrl)//域名
.client(client);//设置okhttp
if (configuration != null)
configuration.configRetrofit(application, builder);
builder
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())//使用 Rxjava
.addConverterFactory(GsonConverterFactory.create(gson));//使用 Gson
return builder.build();
}
@Inject
public DroidKaigiClient(OkHttpClient client) {
Retrofit feedburnerRetrofit = new Retrofit.Builder()
.client(client)
.baseUrl("https://raw.githubusercontent.com")
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(createGson()))
.build();
service = feedburnerRetrofit.create(DroidKaigiService.class);
Retrofit googleFormRetrofit = new Retrofit.Builder()
.client(client)
.baseUrl("https://docs.google.com/forms/d/")
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(createGson()))
.build();
googleFormService = googleFormRetrofit.create(GoogleFormService.class);
Retrofit githubRetrofit = new Retrofit.Builder()
.client(client)
.baseUrl("https://api.github.com")
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(createGson()))
.build();
githubService = githubRetrofit.create(GithubService.class);
}
public void onCustomApiCall(View view) {
final String name = "18688994275";
final String pass = "123456";
final CustomRequest request = EasyHttp.custom()
.addConverterFactory(GsonConverterFactory.create(new Gson()))
.sign(true)
.timeStamp(true)
.params(ComParamContact.Login.ACCOUNT, name)
.params(ComParamContact.Login.PASSWORD, MD5.encrypt4login(pass, AppConstant.APP_SECRET))
.build();
LoginService mLoginService = request.create(LoginService.class);
Observable<AuthModel> observable = request.apiCall(mLoginService.login("v1/account/login", request.getParams().urlParamsMap));
Disposable disposable = observable.subscribe(new Consumer<AuthModel>() {
@Override
public void accept(@NonNull AuthModel authModel) throws Exception {
showToast(authModel.toString());
}
}, new Consumer<Throwable>() {
@Override
public void accept(@NonNull Throwable throwable) throws Exception {
showToast(throwable.getMessage());
}
});
//EasyHttp.cancelSubscription(disposable);//取消订阅
}
/**
* Create a new instance for {@link IMovieDbApi IMovieDbApi} interface.
* The requests will run in OkHttp's internal thread pool.
*/
@NonNull
/* default */ static IMovieDbApi create(@NonNull final OkHttpClient httpClient) {
// Set GSON naming policy
final Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_ENDPOINT)
.addCallAdapterFactory(RxJava2CallAdapterFactory.createAsync()) // Use OkHttp's internal thread pool.
.addConverterFactory(GsonConverterFactory.create(gson))
.client(httpClient)
.build();
return retrofit.create(IMovieDbApi.class);
}
public BookRetrofit() {
context = BookBoxApplication.getInstance().getApplicationContext();
OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
//设置缓存目录
try {
if (context.getCacheDir() != null) {
File cacheDirectory = new File(context.getCacheDir()
.getAbsolutePath(), "HttpCache");
Cache cache = new Cache(cacheDirectory, 20 * 1024 * 1024);
httpClientBuilder.cache(cache);
}
} catch (Exception e) {
e.printStackTrace();
}
okHttpClient = httpClientBuilder.build();
Retrofit retrofit = new Retrofit.Builder()
.client(okHttpClient)
.baseUrl(BASE_API_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
accountApi = retrofit.create(AccountApi.class);
siteApi = retrofit.create(SiteApi.class);
topicApi = retrofit.create(TopicApi.class);
articleApi = retrofit.create(ArticleApi.class);
sysApi = retrofit.create(SysApi.class);
novelApi = retrofit.create(NovelApi.class);
wxArticleApi = retrofit.create(WxArticleApi.class);
jokeApi = retrofit.create(JokeApi.class);
}
@UpdateURL
@Provides
@ActivityScope
Retrofit provideUpdateRetrofit(Retrofit.Builder builder, OkHttpClient client) {
return builder
.baseUrl(UpdateApi.HOST)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
@Provides
@Singleton
ReviewService provideDemoService(OkHttpClient.Builder clientBuilder, Context context, LogWrapper logWrapper) {
//PandroidCall handle Action Delegate on main thread and mock annotation
PandroidCallAdapterFactory factory = PandroidCallAdapterFactory.create(context, logWrapper);
factory.setMockEnable(PandroidConfig.DEBUG);
Retrofit.Builder builder = new Retrofit.Builder()
.client(clientBuilder.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(factory)
.baseUrl(BuildConfig.BASE_URL_PRODUCT);
return builder.build().create(ReviewService.class);
}
private void buildApiClient(String baseUrl) {
apiClient = new Retrofit.Builder()
.baseUrl(baseUrl + "/")
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
.create(ApiClient.class);
}
private void buildApiClient(String baseUrl) {
transactionsApiClient = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
.create(TransactionsApiClient.class);
}
public Twitch(String clientID, String accessToken) {
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new HeaderInterceptor(accessToken, clientID)).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.twitch.tv/kraken/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
this.service = retrofit.create(TwitchService.class);
}
public static RetrofitService getService() {
if (sRetrofit == null) {
synchronized (RetrofitManager.class) {
if (sRetrofit == null) {
sRetrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}
}
return sRetrofit.create(RetrofitService.class);
}
public static Retrofit getInstance(){
if(retrofit == null){
retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
/**
* This method returns retrofit client instance
*
* @return Retrofit object
*/
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
@Provides
@Singleton
Retrofit provideRetrofit() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
return retrofit;
}
@NonNull
private static Retrofit buildRetrofit() {
return new Retrofit.Builder()
.baseUrl(BuildConfig.API_ENDPOINT)
.client(getClient())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
private APIService() {
Retrofit storeRestAPI = new Retrofit.Builder().baseUrl(BASE_URL)
.client(DryInit.mOkHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
apis = storeRestAPI.create(APIs.class);
}
private void buildApiClient(String baseUrl) {
apiClient = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
.create(ApiClient.class);
}
@Singleton
@Provides
static API provideAPI(OkHttpClient client) {
return new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
.create(API.class);
}
public static Retrofit getJokeRetrofit() {
Gson gson = MyGson.get();
OkHttpClient client = MyOkClient.getOkHttpClient();
return new Retrofit.Builder().baseUrl(BuildConfig.BASE_URL_JOKE)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(client)
.build();
}