public FootballDataAPI(Context context) { mContext = context; HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); // set your desired log level logging.setLevel(HttpLoggingInterceptor.Level.BODY); mHttpClient = new OkHttpClient.Builder() .addInterceptor(new HeaderInterceptor()) .addInterceptor(new ApiLimitInterceptor()) .addInterceptor(logging) .build(); // limit the number of concurrent async calls mHttpClient.dispatcher().setMaxRequests(5); Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(mHttpClient) .build(); mApiService = retrofit.create(FootballDataService.class); }
private void getData() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(Constantes.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); PersonAPI personAPI = retrofit.create(PersonAPI.class); Call<List<Person>> persons = personAPI.list(); persons.enqueue( new Callback<List<Person>>() { @Override public void onResponse(Call<List<Person>> call, Response<List<Person>> response) { mPersons = response.body(); createAdapter(); } @Override public void onFailure(Call<List<Person>> call, Throwable t) { Toast.makeText( MainActivity.this, getString(R.string.failure_person_list), Toast.LENGTH_LONG) .show(); } }); }
/** * @param clazz * @param endPoint * @param <T> * @return */ public static <T> T createRetrofitService(final Class<T> clazz, final String endPoint) { final Retrofit.Builder builder = new Retrofit.Builder() .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(endPoint); OkHttpClient client = new OkHttpClient.Builder() .addInterceptor( new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Request newRequest = request .newBuilder() .addHeader("Authorization", "Client-ID " + ImgurService.CLIENT_ID) .build(); return chain.proceed(newRequest); } }) .build(); builder.client(client); T service = builder.build().create(clazz); return service; }
public void testDirectionAsyncQuery() throws IOException { Retrofit retrofit = new Retrofit.Builder() .baseUrl(MapApiService.API_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); MapApiService.DirectionApi directionApi = retrofit.create(MapApiService.DirectionApi.class); String key = mContext.getString(R.string.google_maps_server_key); String origin = "place_id:ChIJAx7UL8xyhlQR86Iqc-fUncc"; String destination = "place_id:ChIJNbea5OF2hlQRDfHhEXerrAM"; Call<MapApiService.TransitRoutes> call = directionApi.getDirections(origin, destination, key); call.enqueue( new Callback<MapApiService.TransitRoutes>() { @Override public void onResponse( Call<MapApiService.TransitRoutes> call, Response<MapApiService.TransitRoutes> response) { if (response.isSuccess()) { MapApiService.TransitRoutes transitRoutes = response.body(); assertTrue( LOG_TAG + ": retrofit query direction status return: " + transitRoutes.status, transitRoutes.status.equals("OK")); } } @Override public void onFailure(Call<MapApiService.TransitRoutes> call, Throwable t) { Timber.d("Error %s", t.getMessage()); } }); }
public RecipeClient() { retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); }
@NonNull private AuthResponse refreshAccessToken(AuthResponse currentAuth) throws IOException, HttpResponseStatusException { OkHttpClient client = OkHttpUtil.getClient(context); Retrofit retrofit = new Retrofit.Builder() .client(client) .baseUrl(config.getApiHostURL()) .addConverterFactory(GsonConverterFactory.create()) .build(); LoginService loginService = retrofit.create(LoginService.class); retrofit2.Response<AuthResponse> refreshTokenResponse; refreshTokenResponse = loginService .refreshAccessToken( "refresh_token", config.getOAuthClientId(), currentAuth.refresh_token) .execute(); if (!refreshTokenResponse.isSuccessful()) { throw new HttpResponseStatusException(refreshTokenResponse.code()); } AuthResponse refreshTokenData = refreshTokenResponse.body(); loginPrefs.storeRefreshTokenResponse(refreshTokenData); return refreshTokenData; }
public static BubblService getClient() { Retrofit retrofit = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .baseUrl(BuildConfig.API_BASE_URL) .build(); BubblService api = retrofit.create(BubblService.class); return api; }
public NetworkService(String baseUrl) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .build(); gitHubRetrofitAPI = retrofit.create(GitHubRetrofitAPI.class); }
@Override public Converter<?, RequestBody> requestBodyConverter( Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { return gsonConverterFactory.requestBodyConverter( type, parameterAnnotations, methodAnnotations, retrofit); }
public PostService() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(ApiConfig.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); postRequest = retrofit.create(PostRequest.class); }
public <S> S createService(Class<S> serviceClass) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASEURL) .client(httpClient.build()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); return retrofit.create(serviceClass); }
/** * Creates a retrofit service from an arbitrary class (clazz) * * @param clazz Java interface of the retrofit service * @param baseUrl REST baseUrl url * @return retrofit service with defined endpoint */ public static <T> T createService(final Class<T> clazz, final String baseUrl) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .build(); return retrofit.create(clazz); }
private RestApi() { OkHttpClient.Builder client = new OkHttpClient.Builder(); client.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS); Retrofit retrofit = new Retrofit.Builder() .client(client.build()) .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); this.mNewsService = retrofit.create(NewsService.class); }
public static CinemalyticsApiService getService() { if (service == null) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(CinemalyticsApiService.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); service = retrofit.create(CinemalyticsApiService.class); } return service; }
public static PacijenteDohvatiAPI getIstance() { if (service == null) { Retrofit retrofit = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .baseUrl(BASE_URL) .build(); service = retrofit.create(PacijenteDohvatiAPI.class); return service; } else { return service; } }
public void testDirectionQuery() throws IOException { Retrofit retrofit = new Retrofit.Builder() .baseUrl(MapApiService.API_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); MapApiService.DirectionApi directionApi = retrofit.create(MapApiService.DirectionApi.class); String key = mContext.getString(R.string.google_maps_server_key); String origin = "place_id:ChIJAx7UL8xyhlQR86Iqc-fUncc"; String destination = "place_id:ChIJNbea5OF2hlQRDfHhEXerrAM"; Call<MapApiService.TransitRoutes> call = directionApi.getDirections(origin, destination, key); MapApiService.TransitRoutes transitRoutes = call.execute().body(); assertTrue( LOG_TAG + ": retrofit query direction status return: " + transitRoutes.status, transitRoutes.status.equals("OK")); }
private TembaAPI getAPIAccessor(String host) { Gson gson = new GsonBuilder() .setExclusionStrategies( new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return f.getDeclaringClass().equals(RealmObject.class); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }) .registerTypeAdapterFactory(new FlowListTypeAdapterFactory()) .create(); HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient.Builder builder = new OkHttpClient.Builder() .readTimeout(60, TimeUnit.SECONDS) .connectTimeout(60, TimeUnit.SECONDS); // add extra logging for debug mode if (BuildConfig.DEBUG) { builder.addInterceptor(interceptor); } final OkHttpClient okHttpClient = builder.build(); try { m_retrofit = new Retrofit.Builder() .baseUrl(host) .addConverterFactory(GsonConverterFactory.create(gson)) .client(okHttpClient) .build(); } catch (IllegalArgumentException e) { throw new TembaException(e); } return m_retrofit.create(TembaAPI.class); }
public static Retrofit getRetrofit() { OkHttpClient client; if (BuildConfig.BUILD_TYPE.equals("debug")) { // chrome://inspect client = new OkHttpClient.Builder().addNetworkInterceptor(new StethoInterceptor()).build(); } else { client = new OkHttpClient(); } return new Retrofit.Builder() .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(SERVER_URL) .client(client) .build(); }
public static IRestService newRestService() { Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").create(); OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(1, TimeUnit.HOURS) .readTimeout(1, TimeUnit.HOURS) .writeTimeout(1, TimeUnit.HOURS) .build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(BuildConfig.ENDPOINT_REST) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(client) .build(); return retrofit.create(IRestService.class); }
@Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ButterKnife.bind(this, view); ctx = getActivity(); feedProgress.bringToFront(); feedRecyclerview.setHasFixedSize(true); mLayoutManager = new LinearLayoutManager(getActivity()); feedRecyclerview.setLayoutManager(mLayoutManager); feedAdapter = new FeedAdapter(getActivity()); feedRecyclerview.setAdapter(feedAdapter); retrofit = new Retrofit.Builder() .baseUrl(Utilitys.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); reqCall = retrofit.create(RequestCallBack.class); IReport application = (IReport) getActivity().getApplication(); mTracker = application.getDefaultTracker(); }
/** Экран входа */ public class MainActivity extends AppCompatActivity { public static final String APP_PREFERENCES = "settings"; public static String APP_PREFERENCES_AUTH = "is_auth"; public static String APP_PREFERENCES_NAME = "name"; public static String APP_PREFERENCES_UID = "uid"; public static SharedPreferences mSettings; private RotateLoading rotateLoading; public static Boolean is_auth; public EditText email; public EditText pass; public String URL = "http://scandinaver.org"; public Gson gson = new GsonBuilder().create(); public Retrofit retrofit = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl(URL) .build(); public ScandinaverAPI API = retrofit.create(ScandinaverAPI.class); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rotateLoading = (RotateLoading) findViewById(R.id.rotateloading); is_auth = false; // проверяем авторизацию в конфиге mSettings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE); if (mSettings.contains(APP_PREFERENCES_AUTH)) is_auth = mSettings.getBoolean(APP_PREFERENCES_AUTH, false); // если авторизован сразу кидаем на второй экран if (is_auth) { Intent intent = new Intent(MainActivity.this, LanguagesActivity.class); startActivity(intent); } email = (EditText) findViewById(R.id.email); pass = (EditText) findViewById(R.id.pass); } @Override public boolean onCreateOptionsMenu(Menu menu) { ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.hide(); } // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void onLogin(View view) throws InterruptedException { rotateLoading.start(); String login = email.getText().toString().isEmpty() ? " " : email.getText().toString(); String password = pass.getText().toString().isEmpty() ? " " : pass.getText().toString(); Call<LoginResponse> call = API.login(login, password); call.enqueue( new Callback<LoginResponse>() { @Override public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) { Log.d("loginresponse", String.valueOf(response.body())); LoginResponse loginresponse = response.body(); if (loginresponse.success()) { Log.d("loginresponse.getId()", String.valueOf(loginresponse.getId())); SharedPreferences.Editor editor = mSettings.edit(); editor.putBoolean(APP_PREFERENCES_AUTH, true); editor.putInt(APP_PREFERENCES_UID, loginresponse.getId()); editor.apply(); Intent intent = new Intent(MainActivity.this, LanguagesActivity.class); startActivity(intent); } else { rotateLoading.stop(); Toast toast = Toast.makeText( getApplicationContext(), "Неправильный логин или пароль", Toast.LENGTH_LONG); toast.show(); } } @Override public void onFailure(Call<LoginResponse> call, Throwable t) { Log.d("onFailureLogin", "onFailureLogin"); rotateLoading.stop(); Toast toast = Toast.makeText( getApplicationContext(), "Неправильный логин или пароль", Toast.LENGTH_LONG); toast.show(); } }); } }
private GsonCustomConverterFactory(Gson gson) { if (gson == null) throw new NullPointerException("gson == null"); this.gson = gson; this.gsonConverterFactory = GsonConverterFactory.create(gson); }
@Override public Converter<ResponseBody, ?> responseBodyConverter( Type type, Annotation[] annotations, Retrofit retrofit) { if (type.equals(String.class)) return new GsonResponseBodyConverterToString<Object>(gson, type); else return gsonConverterFactory.responseBodyConverter(type, annotations, retrofit); }