How to set baseUrl in Retrofit? - java

I want to set the BaseUrl in Retrofit to change dynamically between stage and live because i have an app that has stage and live version. So i made a spinner and the user can select either he wants. But the problem is that after the user select the flavor he wants and then wants to change again it doens't work because the baseUrl is not changing like it should be.
I have this class where is defined the API_URL but it's not working :
#Singleton
class SingleUrlApi {
companion object{
public var API_URL_STAGE = BuildConfig.STAGE
}
}
and then i have another function that uses this API_URL_STAGE
override fun getUrl(shopUrl: ShopUrl, vararg args: String): String {
return when (shopUrl) {
ShopUrl.API_BASE -> if (SingleUrlApi.API_URL_STAGE) {
context.localizedContext(localeManager.getCurrentLocale()).getString(R.string.base_url_stage)
} else {
context.localizedContext(localeManager.getCurrentLocale()).getString(R.string.base_url_live)
}
ShopUrl.WEB_BASE -> if (SingleUrlApi.API_URL_STAGE) {
context.localizedContext(localeManager.getCurrentLocale()).getString(R.string.base_web_url_stage)
} else {
context.localizedContext(localeManager.getCurrentLocale()).getString(R.string.base_web_url_live)
}

You can use OkHttp along with Retrofit.
Then, you can use an OkHttpInterceptor to change the URL of the request
public final class HostSelectionInterceptor implements Interceptor {
#Override public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
String host = //logic to fetch the new URL
if (host != null) {
HttpUrl newUrl = request.url().newBuilder()
.host(host)
.build();
request = request.newBuilder()
.url(newUrl)
.build();
}
return chain.proceed(request);
}
}

An easy and effective way is to use this library: RetrofitUrlManager

Related

How to use Spring OAuth2 Client in SPA and multi-node application?

I want to implement a feature that user connects his account with external applications (similar feature is in Facebook). User has to log in to external application and grant permission to access data by my application.
Once user connected an external app, data will be exchanged in background using access and refresh tokens.
Application architecture is:
SPA front-end (Angular)
REST API (Spring), multiple nodes
ScyllaDB
Envoy proxy (with JWT verification)
The first idea is to use Spring OAuth2 Client. However, some changes need to be made:
there is no Principal because JWT is verified by Envoy proxy and X-USER-ID header is added
REST API is stateless and we shouldn't store authorization code in session
even with sessions, there are multiple nodes and we need to share authorization code between nodes
custom URL, e.g. /app_name/connect instead of /oauth2/authorization/app_name
redirect URL may be invalid (but it's verified by Spring's filter)
How this could work:
user click "Connect with app" in SPA
SPA redirects user to /oauth2/authorization/app_name (or custom URL)
Spring redirects user to external app's authentication server
user authenticates and grants permissions
external app redirects user back to Spring (or straight to SPA?)
Spring redirects user back to SPA (or SPA sends access token to REST API?)
Despite Spring Security components can be replaced, many of them are coupled and you need to rewrite OAuth2 Client flow almost from scratch. Maybe I'm doing something wrong and it can be achieved easier.
What I already did:
http
.cors().and()
.csrf().disable()
.authorizeRequests().anyRequest().permitAll().and()
.oauth2Client(); // get rid of these two filters?
#Configuration
#RequiredArgsConstructor
public class OAuth2ClientConfig {
private final CassandraTemplate cassandraTemplate;
// overriding original client service - we need to store tokens in database
#Bean
public OAuth2AuthorizedClientService authorizedClientService(
CassandraTemplate cassandraTemplate,
ClientRegistrationRepository clientRegistrationRepository) {
return new ScyllaOAuth2AuthorizedClientService(cassandraTemplate, clientRegistrationRepository);
}
// configure client provider to use authorization code with refresh token
#Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
var authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken()
.build();
var authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository,
authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
return authorizedClientManager;
}
// the specs recommend to use WebClient for exchanging data instead of RestTemplate
#Bean
public WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client =
new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
return WebClient.builder()
.apply(oauth2Client.oauth2Configuration())
.build();
}
// override request repository - and I'm stuck there
#Bean
public AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository() {
return new ScyllaOAuth2AuthorizationRequestRepository(cassandraTemplate);
}
}
Because there are multiple nodes of REST API, we can't use sessions. We need to store request somewhere, e.g. ScyllaDB, Redis, Hazelcast, etc. I decided to store it as JSON in ScyllaDB but I ran into trouble.
#Slf4j
#RequiredArgsConstructor
public final class ScyllaOAuth2AuthorizationRequestRepository implements AuthorizationRequestRepository<OAuth2AuthorizationRequest> {
private final CassandraTemplate cassandraTemplate;
private final ObjectMapper objectMapper = new ObjectMapper();
#Override
public OAuth2AuthorizationRequest loadAuthorizationRequest(HttpServletRequest request) {
Assert.notNull(request, "request cannot be null");
var stateParameter = this.getStateParameter(request);
if (stateParameter == null) {
return null;
}
return this.getAuthorizationRequest(request, stateParameter);
}
#Override
public void saveAuthorizationRequest(OAuth2AuthorizationRequest authorizationRequest, HttpServletRequest request,
HttpServletResponse response) {
Assert.notNull(request, "request cannot be null");
Assert.notNull(response, "response cannot be null");
if (authorizationRequest == null) {
this.removeAuthorizationRequest(request, response);
return;
}
var state = authorizationRequest.getState();
var userId = UUID.fromString(request.getHeader(Constants.USER_ID));
Assert.hasText(state, "authorizationRequest.state cannot be empty");
try {
// serialization of Auth2AuthorizationRequest to JSON works
cassandraTemplate.getCqlOperations().execute("insert into oauth2_requests (user_id,state,data) values (?,?,?)",
userId, state, objectMapper.writeValueAsString(authorizationRequest));
} catch (JsonProcessingException e) {
log.warn("Unable to save authorization request", e);
}
}
#Override
public OAuth2AuthorizationRequest removeAuthorizationRequest(HttpServletRequest request) {
Assert.notNull(request, "request cannot be null");
var stateParameter = this.getStateParameter(request);
if (stateParameter == null) {
return null;
}
var userId = UUID.fromString(request.getHeader(Constants.USER_ID));
var originalRequest = this.getAuthorizationRequest(request, stateParameter);
cassandraTemplate.getCqlOperations().execute("delete from oauth2_requests where user_id=? and state=?",
userId, stateParameter);
return originalRequest;
}
private String getStateParameter(HttpServletRequest request) {
return request.getParameter(OAuth2ParameterNames.STATE);
}
private UUID getUserId(HttpServletRequest request) {
return UUID.fromString(request.getHeader(Constants.USER_ID));
}
private OAuth2AuthorizationRequest getAuthorizationRequest(HttpServletRequest request, String state) {
var userId = getUserId(request);
var jsonRequest = cassandraTemplate.getCqlOperations().queryForObject(
"select data from oauth2_requests where user_id=? and state=?", String.class, userId, state);
if (StringUtils.isNotBlank(jsonRequest)) {
try {
// trying to mess with OAuth2ClientJackson2Module
var objectMapper = new Jackson2ObjectMapperBuilder().autoDetectFields(true)
.autoDetectGettersSetters(true)
.modules(new OAuth2ClientJackson2Module())
.visibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY)
.build();
return objectMapper.readValue(jsonRequest, OAuth2AuthorizationRequest.class);
} catch (JsonProcessingException e) {
log.warn("Error decoding authentication request", e);
}
}
return null;
}
}
I get error when trying to deserialize JSON to OAuth2AuthorizationRequest:
Missing type id when trying to resolve subtype of [simple type, class org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest]: missing type id property '#class'
Without adding OAuth2ClientJackson2Module there is another error:
Cannot construct instance of `org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponseType` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)
By the way, OAuth2ClientJackson2Module seems never used in original filters.
Maybe it's better to serialize this object Java way and store it as BLOB or do not store request in database but somewhere other.
Another part is the controller action:
// it had to be /apps/app_name/connect but in Spring OAuth2 Client it's hardcoded to append provider name at the end
#GetMapping("/apps/connect/app_name")
public void connect(HttpServletRequest request, HttpServletResponse response) throws IOException {
userAppService.authorize(request, response, "app_name");
}
To get rid of filters which verify redirect URL and have many things hardcoded:
#Service
#RequiredArgsConstructor
public class UserAppService {
private final HttpSecurity httpSecurity;
private final AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();
private final AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository;
private final ClientRegistrationRepository clientRegistrationRepository;
private final OAuth2AuthorizedClientManager authorizedClientManager;
private final OAuth2AuthorizedClientRepository authorizedClientRepository;
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
public void authorize(HttpServletRequest request, HttpServletResponse response, String appName) throws IOException {
var userId = UUID.fromString(request.getHeader(Constants.USER_ID));
var authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(appName)
.principal(UUIDPrincipal.fromUserId(userId))
.build();
if (isAuthorizationResponse(request)) {
var authorizationRequest = this.authorizationRequestRepository.loadAuthorizationRequest(request);
if (authorizationRequest != null) {
processAuthorizationRequest(request, response);
}
} else {
try {
OAuth2AuthorizedClient authorizedClient = authorizedClientManager.authorize(authorizeRequest);
if (authorizedClient != null) {
OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
System.out.println(accessToken);
}
} catch (ClientAuthorizationException e) {
// in this URL provider name is appended at the end and no way to change this behavior
var authorizationRequestResolver = new DefaultOAuth2AuthorizationRequestResolver(clientRegistrationRepository,
"/apps/connect");
var authorizationRequest = authorizationRequestResolver.resolve(request);
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request, response);
this.redirectStrategy.sendRedirect(request, response, authorizationRequest.getAuthorizationRequestUri());
}
}
}
private void processAuthorizationRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
var authorizationRequest = this.authorizationRequestRepository.removeAuthorizationRequest(request, response);
var registrationId = (String) authorizationRequest.getAttribute(OAuth2ParameterNames.REGISTRATION_ID);
var clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId);
var params = toMultiMap(request.getParameterMap());
var redirectUri = UrlUtils.buildFullRequestUrl(request);
var authorizationResponse = convert(params, redirectUri);
var authenticationRequest = new OAuth2AuthorizationCodeAuthenticationToken(
clientRegistration, new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse));
authenticationRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
OAuth2AuthorizationCodeAuthenticationToken authenticationResult;
try {
var authenticationManager = httpSecurity.getSharedObject(AuthenticationManager.class);
authenticationResult = (OAuth2AuthorizationCodeAuthenticationToken) authenticationManager
.authenticate(authenticationRequest);
} catch (OAuth2AuthorizationException ex) {
OAuth2Error error = ex.getError();
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(authorizationRequest.getRedirectUri())
.queryParam(OAuth2ParameterNames.ERROR, error.getErrorCode());
if (!StringUtils.hasText(error.getDescription())) {
uriBuilder.queryParam(OAuth2ParameterNames.ERROR_DESCRIPTION, error.getDescription());
}
if (!StringUtils.hasText(error.getUri())) {
uriBuilder.queryParam(OAuth2ParameterNames.ERROR_URI, error.getUri());
}
this.redirectStrategy.sendRedirect(request, response, uriBuilder.build().encode().toString());
return;
}
// just copy-paste of original filter - trying to understand what's happening there
Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication();
String principalName = (currentAuthentication != null) ? currentAuthentication.getName() : "anonymousUser";
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(
authenticationResult.getClientRegistration(), principalName, authenticationResult.getAccessToken(),
authenticationResult.getRefreshToken());
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, currentAuthentication, request,
response);
String redirectUrl = authorizationRequest.getRedirectUri();
this.redirectStrategy.sendRedirect(request, response, redirectUrl);
}
private static boolean isAuthorizationResponse(HttpServletRequest request) {
return isAuthorizationResponseSuccess(request) || isAuthorizationResponseError(request);
}
private static boolean isAuthorizationResponseSuccess(HttpServletRequest request) {
return StringUtils.hasText(request.getParameter(OAuth2ParameterNames.CODE))
&& StringUtils.hasText(request.getParameter(OAuth2ParameterNames.STATE));
}
private static boolean isAuthorizationResponseError(HttpServletRequest request) {
return StringUtils.hasText(request.getParameter(OAuth2ParameterNames.ERROR))
&& StringUtils.hasText(request.getParameter(OAuth2ParameterNames.STATE));
}
// copy paste - not tested this code yet
static MultiValueMap<String, String> toMultiMap(Map<String, String[]> map) {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>(map.size());
map.forEach((key, values) -> {
if (values.length > 0) {
for (String value : values) {
params.add(key, value);
}
}
});
return params;
}
static OAuth2AuthorizationResponse convert(MultiValueMap<String, String> request, String redirectUri) {
String code = request.getFirst(OAuth2ParameterNames.CODE);
String errorCode = request.getFirst(OAuth2ParameterNames.ERROR);
String state = request.getFirst(OAuth2ParameterNames.STATE);
if (StringUtils.hasText(code)) {
return OAuth2AuthorizationResponse.success(code).redirectUri(redirectUri).state(state).build();
}
String errorDescription = request.getFirst(OAuth2ParameterNames.ERROR_DESCRIPTION);
String errorUri = request.getFirst(OAuth2ParameterNames.ERROR_URI);
return OAuth2AuthorizationResponse.error(errorCode)
.redirectUri(redirectUri)
.errorDescription(errorDescription)
.errorUri(errorUri)
.state(state)
.build();
}
}
Client service to stored authorized clients in database:
#RequiredArgsConstructor
public class ScyllaOAuth2AuthorizedClientService implements OAuth2AuthorizedClientService {
private final CassandraTemplate cassandraTemplate;
private final ClientRegistrationRepository clientRegistrationRepository;
#Override
#SuppressWarnings("unchecked")
public OAuth2AuthorizedClient loadAuthorizedClient(String clientRegistrationId, String principal) {
var id = BasicMapId.id("userId", principal).with("appCode", clientRegistrationId);
var userApp = cassandraTemplate.selectOneById(id, UserApp.class);
if (userApp != null) {
var clientRegistration = getClientRegistration(clientRegistrationId);
var accessToken = getAccessToken(userApp);
var refreshToken = getRefreshToken(userApp);
return new OAuth2AuthorizedClient(clientRegistration, principal, accessToken, refreshToken);
} else {
return null;
}
}
#Override
public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
Assert.notNull(authorizedClient, "authorizedClient cannot be null");
Assert.notNull(principal, "principal cannot be null");
var userApp = new UserApp();
userApp.setUserId((UUID) principal.getPrincipal());
userApp.setAppCode(authorizedClient.getClientRegistration().getClientId());
if (authorizedClient.getAccessToken() != null) {
userApp.setAccessToken(authorizedClient.getAccessToken().getTokenValue());
userApp.setAccessTokenType(OAuth2AccessToken.TokenType.BEARER.getValue());
userApp.setAccessTokenScopes(authorizedClient.getAccessToken().getScopes());
userApp.setAccessTokenIssuedAt(authorizedClient.getAccessToken().getIssuedAt());
userApp.setAccessTokenExpiresAt(authorizedClient.getAccessToken().getExpiresAt());
}
if (authorizedClient.getRefreshToken() != null) {
userApp.setRefreshToken(authorizedClient.getRefreshToken().getTokenValue());
userApp.setRefreshTokenIssuedAt(authorizedClient.getRefreshToken().getIssuedAt());
userApp.setRefreshTokenExpiresAt(authorizedClient.getRefreshToken().getExpiresAt());
}
cassandraTemplate.insert(userApp);
}
#Override
public void removeAuthorizedClient(String clientRegistrationId, String principal) {
var id = BasicMapId.id("userId", principal).with("appCode", clientRegistrationId);
cassandraTemplate.deleteById(id, UserApp.class);
}
private ClientRegistration getClientRegistration(String clientRegistrationId) {
var clientRegistration = this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId);
if (clientRegistration == null) {
throw new DataRetrievalFailureException(
"The ClientRegistration with id '" + clientRegistrationId + "' exists in the data source, "
+ "however, it was not found in the ClientRegistrationRepository.");
}
return clientRegistration;
}
private OAuth2AccessToken getAccessToken(UserApp userApp) {
return new OAuth2AccessToken(
OAuth2AccessToken.TokenType.BEARER,
userApp.getAccessToken(),
userApp.getAccessTokenIssuedAt(),
userApp.getAccessTokenExpiresAt(),
userApp.getAccessTokenScopes());
}
private OAuth2RefreshToken getRefreshToken(UserApp userApp) {
return new OAuth2RefreshToken(userApp.getRefreshToken(), userApp.getRefreshTokenIssuedAt());
}
}
Too much code overwrite. I need to make it as simple as possible.
Currently I'm struggling with storing authorize request in database.
How to do it Spring way but to keep the app architecture given at the beginning of this question?
Any way to configure OAuth2 Client without hardcoded URL like /oauth2/authorization/provider_name?
Maybe it's better to do the whole OAuth2 flow client-side (within SPA) and the SPA should send access and request token to REST API (to store the tokens in order to be able to exchange data with external app)?
In OAuth2 wording, REST APIs are resource-servers, not clients.
What you can do is have
your proxy be transparent to OAuth2 (forward requests with their JWT access-token authorization header and responses status code)
configure each REST API as resource-server. Tutorials there: https://github.com/ch4mpy/spring-addons/tree/master/samples/tutorials.
add an OAuth2 client library to your Angular app to handle tokens and authorize requests. My favorite is angular-auth-oidc-client
probably use an intermediate authorization-server for identity federation (Google, Facebook, etc., but also internal DB, LDAP, or whatever is needed), roles management, MFA,... Keycloak is a famous "on premise" solution, but you can search for "OIDC authorization-server" in your favorite search engine and have plenty of alternate choices, including SaaS like Auth0 or Amazon Cognito.
This is fully compatible with distributed architectures and micro-services (session-less is the default configuration for resource-servers in the tutorials I linked).
Two cases for a micro-service delegating some of its processing to another resource-server:
the "child" request is made on behalf of the user who initiated the request => retrieve original access-token from Authentication instance in security-context and forward it (set it as Bearer authorization header for the sub-request)
the "child" request is not made on behalf of a user => client-credentials must be used (the micro-services acquires a new access-token in its own name to authorize the sub request). Refer to spring-boot-oauth2-client and your preferred REST client docs for details (WebClient, #FeignClient, RestTemplate).

Issues using Retrofit2 to call GitHub REST API to update existing file

I'm attempting to use Retrofit to call the GitHub API to update the contents of an existing file, but am getting 404s in my responses. For this question, I'm interested in updating this file. Here is the main code I wrote to try and achieve this:
GitHubUpdateFileRequest
public class GitHubUpdateFileRequest {
public String message = "Some commit message";
public String content = "Hello World!!";
public String sha = "shaRetrievedFromSuccessfulGETOperation";
public final Committer committer = new Committer();
private class Committer {
Author author = new Author();
private class Author {
final String name = "blakewilliams1";
final String email = "blake#blakewilliams.org";
}
}
}
**GitHubUpdateFileResponse **
public class GitHubUpdateFileResponse {
public GitHubUpdateFileResponse() {}
}
GitHubClient
public interface GitHubClient {
// Docs: https://docs.github.com/en/rest/reference/repos#get-repository-content
// WORKS FINE
#GET("/repos/blakewilliams1/blakewilliams1.github.io/contents/qr_config.json")
Call<GitHubFile> getConfigFile();
// https://docs.github.com/en/rest/reference/repos#create-or-update-file-contents
// DOES NOT WORK
#PUT("/repos/blakewilliams1/blakewilliams1.github.io/contents/qr_config.json")
Call<GitHubUpdateFileResponse> updateConfigFile(#Body GitHubUpdateFileRequest request);
}
Main Logic
// Set up the Retrofit client and add an authorization interceptor
UserAuthInterceptor interceptor =
new UserAuthInterceptor("blake#blakewilliams.org", "myActualGitHubPassword");
OkHttpClient.Builder httpClient =
new OkHttpClient.Builder().addInterceptor(interceptor);
Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.client(httpClient.build()).build();
client = retrofit.create(GitHubClient.class);
// Now make the request and process the response
GitHubUpdateFileRequest request = new GitHubUpdateFileRequest();
client.updateConfigFile(request).enqueue(new Callback<GitHubUpdateFileResponse>() {
#Override
public void onResponse(Call<GitHubUpdateFileResponse> call, Response<GitHubUpdateFileResponse> response) {
int responseCode = response.code();
// More code on successful update
}
#Override
public void onFailure(Call<GitHubUpdateFileResponse> call, Throwable t) {
Log.e("MainActivity", "Unable to update file" + t.getLocalizedMessage());
}
});
What currently happens:
Currently, the success callback is triggered, but with a response code of 404 like so:
Response{protocol=http/1.1, code=404, message=Not Found, url=https://api.github.com/repos/blakewilliams1/blakewilliams1.github.io/contents/qr_config.json}
Has anyone else encountered this? I first thought it was a problem with including '/content/' in the URL but I do the same thing for reading the file contents request and it works fine (also uses same URL just a GET instead of PUT).
For anyone interested in doing this in the future, I figured out the solution.
I needed to revise the request object structure
Rather than using an authentication interceptor, I instead added an access token to the header. Here is where you can create access tokens for Github, you only need to grant it permissions to the 'repos' options for this use case to work.
This is what my updated request object looks like:
public class GitHubUpdateFileRequest {
public String message;
public String content;
public String sha;
public final Committer committer = new Committer();
public GitHubUpdateFileRequest(String unencodedContent, String message, String sha) {
this.message = message;
this.content = Base64.getEncoder().encodeToString(unencodedContent.getBytes());
this.sha = sha;
}
private static class Committer {
final String name = "yourGithubUsername";
final String email = "email#yourEmailAddressForTheUsername.com";
}
}
Then from my code, I would just say:
GitHubUpdateFileRequest updateRequest = new GitHubUpdateFileRequest("Hello World File Contents", "This is the title of the commit", shaOfExistingFile);
For using this reqest, I updated the Retrofit client implementation like so:
// https://docs.github.com/en/rest/reference/repos#create-or-update-file-contents
#Headers({"Content-Type: application/vnd.github.v3+json"})
#PUT("/repos/yourUserName/yourRepository/subfolder/path/to/specific/file/theFile.txt")
Call<GitHubUpdateFileResponse> updateConfigFile(
#Header("Authorization") String authorization, #Body GitHubUpdateFileRequest request);
And I call that interface like this:
githubClient.updateConfigFile("token yourGeneratedGithubToken", request);
And yes, you do need the prefix "token ". You could hardcode that header into the interface, but I pass it in so that I can store it in locations outside of my version control's reach for security reasons.

How to Change API Base Url at Runtime(Retrofit,Android,Java)?

I need to change base url at run time.
I have login button and when login button click time i am called my login api
like below :
login api = http://192.168.0.61/api/authenticate
API_BASE_URL = http://192.168.0.61/api/
when i get success response from first api i get client server url for changing baseUrl.
CompanyUrlConfigEntity companyUrlConfigEntity = response.body();
like below :
String clientUrl = companyUrlConfigEntity.
getBaseUrl();
clientUrl = http://192.168.0.238/api/
In this project mainly for client or company based.So they have their own server.
Each company has using more than 20 api's.
So i need to change base url .
I am also checked below link for changing base url:
https://futurestud.io/tutorials/retrofit-2-how-to-change-api-base-url-at-runtime-2
and changed code like that
public static void changeApiBaseUrl(String newApiBaseUrl) {
API_BASE_URL = newApiBaseUrl;
builder = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(new NullOnEmptyConverterFactory())
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(new Gson()));
}
when i debugged and checked my baseUrl then it shows properly like below:
API_BASE_URL = http://192.168.0.238/api/
But when i call my customer api it shows the my first base url calling,
the url not changed.
expected customer api : http://192.168.0.238/api/customers
reality customer api : http://192.168.0.61/api/customers
I am also checked below link :
https://futurestud.io/tutorials/retrofit-2-how-to-use-dynamic-urls-for-requests
thats working , But each api need to pass fullPath url with each api like below:
#GET
public Call<ResponseBody> profilePicture(#Url String url);
But using this method , each api calling place i need to attach full path of url.
There is any other options? Please help me.
ServiceGenerator.class
public class ServiceGenerator {
public static String API_BASE_URL = "http://192.168.0.61/api/";
private static Retrofit retrofit;
private static OkHttpClient.Builder httpClient = new
OkHttpClient.Builder();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(new NullOnEmptyConverterFactory())
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(new
Gson()));
private ServiceGenerator() {
}
public static void changeApiBaseUrl(String newApiBaseUrl) {
API_BASE_URL = newApiBaseUrl;
builder = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(new NullOnEmptyConverterFactory())
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(new Gson()));
}
public static Retrofit retrofit() {
return retrofit;
}
public static <S> S createService(Class<S> serviceClass) {
return createService(serviceClass, null, null);
}
public static <S> S createService(Class<S> serviceClass,
final String authToken,
final ProgressListener progressListener) {
if (authToken != null) {
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
final String headerValue = AUTHORIZATION_TYPE + authToken;
Request request = original.newBuilder()
.header(AUTHORIZATION_HEADER_KEY, headerValue)
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
});
}
addResponseProgressListener(progressListener);
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor httpLoggingInterceptor = new
HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(httpLoggingInterceptor);
}
if (authToken != null) {
if (picasso == null) {
setUpPicasso(authToken);
}
}
OkHttpClient client = httpClient.build();
httpClient.connectTimeout(15, TimeUnit.SECONDS);
httpClient.readTimeout(2, TimeUnit.MINUTES);
httpClient.writeTimeout(2, TimeUnit.MINUTES);
retrofit = builder.client(client).build();
return retrofit.create(serviceClass);
}
}
LoginFragment.java
#OnClick(R.id.bt_login)
void onLogin() {
checkValidityOfUser();
}
private void checkValidityOfUser() {
final Login login = getLoginCredentials();
Call<CompanyUrlConfigEntity> callCheckValidity = dataProcessController.
getApiClient().
checkValidityOfUsers(login.getUsername());
callCheckValidity.enqueue(new Callback<CompanyUrlConfigEntity>() {
#Override
public void onResponse(Call<CompanyUrlConfigEntity> call,
Response<CompanyUrlConfigEntity> response) {
if (response.code() == 200) {
CompanyUrlConfigEntity companyUrlConfigEntity = response.body();
boolean status = companyUrlConfigEntity.isValidUser();
if (status) {
String baseUrls = companyUrlConfigEntity.
getBaseUrl();
baseUrls = baseUrls + "/api/";
ServiceGenerator.changeApiBaseUrl(baseUrls);
logins();
} else {
ToastHelper.show("please contact admin");
}
} else {
ToastHelper.show("" + response.code() + response.message());
}
}
#Override
public void onFailure(Call<CompanyUrlConfigEntity> call, Throwable t) {
ToastHelper.show("please contact admin");
}
});
}
private void logins() {
login = getLoginCredentials();
Call<Void> callLogin = dataProcessController.
getApiClient().
login(login);
callLogin.enqueue(new Callback<Void>() {
#Override
public void onResponse(Call<Void> call, Response<Void> response) {
if (response.code() == 200) {
} else if (response.code() == 401) {
}
}
#Override
public void onFailure(Call<Void> call, Throwable t) {
}
});
}
Base on your comments, I would say that you are correctly changing the API url on your builder, but that your second call still uses an instance of service where the url has not changed.
To explain a little more, from what I understand this is how everything gets executed:
when fragment is created, the apiClient is created and pointing to the first url
with dataProcessController.getApiClient() in your first call, you are getting the service that is pointing to the first url and then execute the call.
when the call is successful, you read the new url from result and update the ServiceGenerator with that new url. Then you execute the logins() method.
and in that method, you recall the dataProcessController.getApiClient() and do the second call with it. However, as you never redid apiClient = ServiceGenerator.createService(ApiClient.class);, the apiClient instance you are getting is still pointing to the first url, because it hasn't been notified that the url changed.
What I would try here, would be to change the method getApiClient() in your DataProcessController class to something like this:
public ApiClient getApiClient() {
apiClient = ServiceGenerator.createService(ApiClient.class);
return apiClient;
}
and see if this is work better.
Or if you don't want to regenerate the service inside that function, you can also do something like this:
public class DataProcessController {
private ApiClient apiClient = null;
private DataProcessController() {
regenerateClient();
}
public ApiClient getApiClient() { return apiClient; }
// add this to regenerate the client whenever url changes
public void regenerateClient() {
apiClient = ServiceGenerator.createService(ApiClient.class);
}
}
then, everytime you do change the url, do this:
ServiceGenerator.changeApiBaseUrl(baseUrls);
dataProcessController.regenerateClient();
and you should get a client that points to the correct url everytime you do dataProcessController.getApiClient()
https://segunfamisa.com/posts/firebase-remote-config
You should follow concept of firebase remote config. Here you dont need to store base Url in source code it will be retrieved from firebase config values which is stored at server of firebase.
// fetch
mRemoteConfig.fetch(3000)
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
// update your base url here.
} else {
//task failed
}
}
});

refresh token rxjava+retrofir2

When registering in the application user gets 2 tokens. Access (lives 1 day) and Refresh (lives 6 months). At a certain point, the Access token will come-one day there will be a custom error. At this , we need to call the refreshToken method and the updated , with which the work will go on.
We call the method, for example getdata , checking for errors, if custom error refreshToken we keep both tokens getdata already with the updated token.
i try but how to rerty call method getdata after refresh token?
mAllApi.getData(new Request().getRequestData())
.flatMap(response -> {
if (response.getError().equals(ECode.ERROR_TOKEN.getCode())) {
mAllApi.getRefreshToken(new String()).flatMap(new Function<AccessToken, ObservableSource<AccessToken>>() {
#Override
public ObservableSource<AccessToken> apply(AccessToken accessToken) throws Exception {
AccessTokenManager.saveNewAccessToken(accessToken);
return null;
}
});
} else {
return Observable.just(response);
}
});
What we did in our app - we created custom OkHttp Interceptor which checks for Access Token each time we do Auth Request and if it's corrupted Interceptor change it with RefreshToken, Add new updated value to Authorization Header and retries Request.
Here is example in Kotlin:
class RefreshAccessTokenInterceptor
#Inject constructor() : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val response = chain.proceed(retryRequest(chain))
return if (response.noAuthError()) {
response
} else {
updateIfNeededOrProcessWithNewToken(chain)
}
}
private fun retryRequest(chain: Interceptor.Chain): Request {
val builder = chain.request().newBuilder()
addAuthHeaders(builder)
return builder.build()
}
private fun Response.noAuthError() = code() != HttpErrorChecker.HTTP_AUTHENTICATION_TIMEOUT
private fun addAuthHeaders(builder: Request.Builder) {
val accessToken = getAccessToken()
if (!accessToken.isNullOrEmpty()) {
builder.header("Authorization", "Bearer $accessToken")
}
}
private fun updateIfNeededOrProcessWithNewToken(chain: Interceptor.Chain): Response {
//here you update your token, add new header and retries request
return chain.proceed(retryRequest(chain))
}
}

Using Retrofit in Android

I have an android app that has 3 activities :
A login activity
A tasks acivity where all tasks pertaining to a user are displayed (Populated using an Array Adapter)
A task_details activity which results from clicking a task on the list
I have to consume REST Apis. The research I have done so far directs me to use Retrofit. I checked how to use it and found out that :
Set the base URL in the Main Activity (Mine is the Login Activity)
I need to create a API class and define my functions using annotations.
Use the class Rest Adapter in the Activity and define Callbacks.
Had my app been a single activity app, I would have crunched everything in my MainActivity.java but I don't know how and where to put all the code from steps 1,2,3 for use in my 3 activities.Could you please help by telling how to use Retrofit in my app. Thanks a lot.
Specifically, I need network calls to :
1. Login the user
2. Get all the tasks of the user.
And for both I would be using a given REST api.
*********************************************
Calling Api USing Retrofit
*********************************************
**Dependancies** :-
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.android.support:cardview-v7:27.1.1'
enter code here
**Model**
use the Pozo class
**Api Call**
-> getLogin() // use the method
//API call for Login
private void getLogin()
{
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
AsyncHttpClient client = new AsyncHttpClient();
RequestParams requestParams = new RequestParams();
requestParams.put("email_id", edit_email.getText().toString());
requestParams.put("password", edit_password.getText().toString());
Log.e("", "LOGIN URL==>" + Urls.LOGIN + requestParams);
Log.d("device_token", "Device_ Token" + FirebaseInstanceId.getInstance().getToken());
client.post(Urls.LOGIN, requestParams, new JsonHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
ShowProgress();
}
#Override
public void onFinish() {
super.onFinish();
Hideprogress();
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.e("", "Login RESPONSE-" + response);
Login login = new Gson().fromJson(String.valueOf(response), Login.class);
edit_email.setText("");
edit_password.setText("");
if (login.getStatus().equals("true")) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("User Login Successfully!"),
MDToast.LENGTH_SHORT, MDToast.TYPE_SUCCESS);
mdToast.show();
Utils.WriteSharePrefrence(SignInActivity.this, Util_Main.Constant.EMAIL, login.getData().getEmailId());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERID, login.getData().getId());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERNAME, login.getData().getFirstName());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.PROFILE, login.getData().getProfileImage());
hideKeyboard(SignInActivity.this);
Intent intent = new Intent(SignInActivity.this, DashboardActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("Login Denied"),
MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e("", throwable.getMessage());
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, "Something went wrong",
MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();
}
});
}
Using Retrofit is quite simple and straightforward.
First of all you need to add retrofit to your project, as example with Gradle build sytem.
compile 'com.squareup.retrofit:retrofit:1.7.1' |
another way you can download .jar and place it to your libs folder.
Then you need to define interfaces that will be used by Retrofit to make API calls to your REST endpoints. For example for users:
public interface YourUsersApi {
//You can use rx.java for sophisticated composition of requests
#GET("/users/{user}")
public Observable<SomeUserModel> fetchUser(#Path("user") String user);
//or you can just get your model if you use json api
#GET("/users/{user}")
public SomeUserModel fetchUser(#Path("user") String user);
//or if there are some special cases you can process your response manually
#GET("/users/{user}")
public Response fetchUser(#Path("user") String user);
}
Ok. Now you have defined your API interface an you can try to use it.
To start you need to create an instance of RestAdapter and set base url of your API back-end. It's also quite simple:
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://yourserveraddress.com")
.build();
YourUsersApi yourUsersApi = restAdapter.create(YourUsersApi.class);
Here Retrofit will read your information from interface and under the hood it will create RestHandler according to meta-info your provided which actually will perform HTTP requests.
Then under the hood, once response is received, in case of json api your data will be transformed to your model using Gson library so you should be aware of that fact that limitations that are present in Gson are actually there in Retrofit.
To extend/override process of serialisers/deserialisation your response data to your models you might want to provide your custom serialisers/deserialisers to retrofit.
Here you need to implement Converter interface and implement 2 methods fromBody() and toBody().
Here is example:
public class SomeCustomRetrofitConverter implements Converter {
private GsonBuilder gb;
public SomeCustomRetrofitConverter() {
gb = new GsonBuilder();
//register your cursom custom type serialisers/deserialisers if needed
gb.registerTypeAdapter(SomeCutsomType.class, new SomeCutsomTypeDeserializer());
}
public static final String ENCODING = "UTF-8";
#Override
public Object fromBody(TypedInput body, Type type) throws ConversionException {
String charset = "UTF-8";
if (body.mimeType() != null) {
charset = MimeUtil.parseCharset(body.mimeType());
}
InputStreamReader isr = null;
try {
isr = new InputStreamReader(body.in(), charset);
Gson gson = gb.create();
return gson.fromJson(isr, type);
} catch (IOException e) {
throw new ConversionException(e);
} catch (JsonParseException e) {
throw new ConversionException(e);
} finally {
if (isr != null) {
try {
isr.close();
} catch (IOException ignored) {
}
}
}
}
#Override
public TypedOutput toBody(Object object) {
try {
Gson gson = gb.create();
return new JsonTypedOutput(gson.toJson(object).getBytes(ENCODING), ENCODING);
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
}
private static class JsonTypedOutput implements TypedOutput {
private final byte[] jsonBytes;
private final String mimeType;
JsonTypedOutput(byte[] jsonBytes, String encode) {
this.jsonBytes = jsonBytes;
this.mimeType = "application/json; charset=" + encode;
}
#Override
public String fileName() {
return null;
}
#Override
public String mimeType() {
return mimeType;
}
#Override
public long length() {
return jsonBytes.length;
}
#Override
public void writeTo(OutputStream out) throws IOException {
out.write(jsonBytes);
}
}
}
And now you need to enable your custom adapters, if it was needed by using setConverter() on building RestAdapter
Ok. Now you are aware how you can get your data from server to your Android application. But you need somehow mange your data and invoke REST call in right place.
There I would suggest to use android Service or AsyncTask or loader or rx.java that would query your data on background thread in order to not block your UI.
So now you can find the most appropriate place to call
SomeUserModel yourUser = yourUsersApi.fetchUser("someUsers")
to fetch your remote data.
I have just used retrofit for a couple of weeks and at first I found it hard to use in my application. I would like to share to you the easiest way to use retrofit in you application. And then later on if you already have a good grasp in retrofit you can enhance your codes(separating your ui from api and use callbacks) and maybe get some techniques from the post above.
In your app you have Login,Activity for list of task,and activity to view detailed task.
First thing is you need to add retrofit in your app and theres 2 ways, follow #artemis post above.
Retrofit uses interface as your API. So, create an interface class.
public interface MyApi{
/*LOGIN*/
#GET("/api_reciever/login") //your login function in your api
public void login(#Query("username") String username,#Query("password") String password,Callback<String> calback); //this is for your login, and you can used String as response or you can use a POJO, retrofit is very rubust to convert JSON to POJO
/*GET LIST*/
#GET("/api_reciever/getlist") //a function in your api to get all the list
public void getTaskList(#Query("user_uuid") String user_uuid,Callback<ArrayList<Task>> callback); //this is an example of response POJO - make sure your variable name is the same with your json tagging
/*GET LIST*/
#GET("/api_reciever/getlistdetails") //a function in your api to get all the list
public void getTaskDetail(#Query("task_uuid") String task_uuid,Callback<Task> callback); //this is an example of response POJO - make sure your variable name is the same with your json tagging
}
Create another interface class to hold all your BASE ADDRESS of your api
public interface Constants{
public String URL = "www.yoururl.com"
}
In your Login activity create a method to handle the retrofit
private void myLogin(String username,String password){
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(Constants.URL) //call your base url
.build();
MyApi mylogin = restAdapter.create(MyApi.class); //this is how retrofit create your api
mylogin.login(username,password,new Callback<String>() {
#Override
public void success(String s, Response response) {
//process your response if login successfull you can call Intent and launch your main activity
}
#Override
public void failure(RetrofitError retrofitError) {
retrofitError.printStackTrace(); //to see if you have errors
}
});
}
In your MainActivityList
private void myList(String user_uuid){
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(Constants.URL) //call your base url
.build();
MyApi mytask = restAdapter.create(MyApi.class); //this is how retrofit create your api
mytask.getTaskDetail(user_uuid,new Callback<Task>>() {
#Override
public void success(ArrayList<Task> list, Response response) {
//process your response if successful load the list in your listview adapter
}
#Override
public void failure(RetrofitError retrofitError) {
retrofitError.printStackTrace(); //to see if you have errors
}
});
}
In your Detailed List
private void myDetailed(String task_uuid){
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(Constants.URL) //call your base url
.build();
MyApi mytask = restAdapter.create(MyApi.class); //this is how retrofit create your api
mytask.getTaskList(task_uuid,new Callback<Task>() {
#Override
public void success(Task task, Response response) {
//process your response if successful do what you want in your task
}
#Override
public void failure(RetrofitError retrofitError) {
retrofitError.printStackTrace(); //to see if you have errors
}
});
}
Hope this would help you though its really the simplest way to use retrofit.
Take a look at this , excellent blog on using Retrofit in conjunction with Otto, both libraries are from Square.
http://www.mdswanson.com/blog/2014/04/07/durable-android-rest-clients.html
The basic idea is that you will hold a reference to a "repository" object in your Application class. This object will have methods that "subscribe" to rest api event requests. When one is received it will make the proper Retrofit call, and then "post" the response, which can then be "subscribed" to by another component (such as the activity that made the request).
Once you have this all setup properly, accessing data via your rest api becomes very easy. For example, making are request for data would look something like this :
mBus.post(new GetMicropostsRequest(mUserId));
and consuming the data would look something like this:
#Subscribe
public void onGetUserProfileResponse(GetUserProfileResponse event) {
mView.setUserIcon("http://www.gravatar.com/avatar/" + event.getGravatar_id());
mView.setUserName(event.getName());
}
It takes a little bit of upfront effort, but in the end it becomes "trivial" to access anything you need from our backend via Rest.
You may try saving references to your api inside your application class. Then you can get it's instance from any activity or fragment and get api from there. That sounds a little weird, but it may be a simple DI alternative. And if you will only store references in your app class, it won't be a kind of god object
UPD: http://square.github.io/retrofit/ - here is some documentation, it might be useful
Using RetroFit is very easy.
Add dependecy in build.gradle.
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.squareup.okhttp:okhttp:2.4.0'
Make an Interface for all http methods.
Copy your json output and create pojo class to recieve json of your
response, you can make pojo from JsonSchema2pojo site .
make an adapter and call your method
for complete demo try this tutorial Retrofit Android example
Checkout this app that demonstrates Retrofit integration to Google Tasks API.
https://github.com/sschendel/SyncManagerAndroid-DemoGoogleTasks
There are examples of Retrofit api (TaskApi) used within Activity AsyncTask in MainActivity, as well as examples of use within Sync Adapter in background service.
The strategy from the article posted in #nPn's answer is probably a more elegant solution, but you can at least look at another working example.
Firstly, putting everything in MainActivity would be bad practice and you would end up with a God object.
The documentation on the Retrofit site is fantastic, so I'm going to read your question on how to structure the project. I wrote a very small app for demonstration purposes. It loads cats from the cat API and should be fairly simple to follow what is happening.
It has an example of using JSON or XML for the parsing of data from the service. You can find it at https://github.com/codepath/android_guides/wiki/Consuming-APIs-with-Retrofit
Hopefully you can extrapolate why I have structured it the way I have. I'm happy to answer any questions you have in the comments and update the answer.
I find these tutorials AndroidHive , CodePath helpful
I will briefly describe what I have learned.
Step 1 : Add these three dependencies to build.gradle and Add Internet permission to Manifest
compile 'com.google.code.gson:gson:2.6.2' // for string to class conversion. Not Compulsory
compile 'com.squareup.retrofit2:retrofit:2.1.0'// compulsory
compile 'com.squareup.retrofit2:converter-gson:2.1.0' //for retrofit conversion
Add them in Manifest
<uses-permission android:name="android.permission.INTERNET" />
Step 2
Creae ApiClient and ApiInterface.
public class ApiClient {
public static final String BASE_URL = "http://yourwebsite/services/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
where ApiInterface.class
public interface ApiInterface {
// getting same data in three different ways.
#GET("GetCompanyDetailByID")
Call<CompanyResponse> getDetailOfComapanies(#Query("CompanyID") int companyID);
#GET("GetCompanyDetailByID")
Call<ResponseBody> getRawDetailOfCompanies(#Query("CompanyID") int companyID);
#GET("{pathToAdd}")
Call<CompanyResponse> getDetailOfComapaniesWithPath(#Path("pathToAdd") String pathToAppend, #Query("CompanyID") int companyID);
}
And call this service like
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<CompanyResponse> companyResponseCall = apiService.getDetailOfComapanies(2);
//Call<CompanyResponse> companyResponseCall = apiService.getDetailOfComapaniesWithPath("GetCompanyDetailByID",2);
companyResponseCall.enqueue(new Callback<CompanyResponse>() {
#Override
public void onResponse(Call<CompanyResponse> call, Response<CompanyResponse> response) {
CompanyResponse comapnyResponse = response.body();
Boolean status = comapnyResponse.getStatus();
}
#Override
public void onFailure(Call<CompanyResponse> call, Throwable t) {
}
});
For Getting Raw Json String
Call<ResponseBody> call = apiService.getRawDetailOfCompanies(2);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
String jsonStr = response.body().string();
if(!jsonStr.isEmpty()){
Gson gson = new Gson();
JSONObject jObject = new JSONObject(jsonStr).getJSONObject("data");
//1st Method
Data dataKiType = gson.fromJson(jObject.toString(), Data.class);
dataKiType.getCompanyDetail();
//2nd method for creaing class or List at runTime
Type listType = new TypeToken<Data>(){}.getType();
Data yourClassList = new Gson().fromJson(jObject.toString(), listType);
yourClassList.getCompanyDetail();
} e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
You can create your business object using http://www.jsonschema2pojo.org/ by simply pasting json. and selecting source type to JSON and Annotation Style to GSon
Found a small, but complete and concise example at
https://github.com/square/retrofit/tree/master/samples
Beginners find it little intimidating to learn retrofit. I have prepared a tutorial which will simplify the learning curve. See Retrofit android tutorial for more information.
Developing your own type-safe HTTP library to interface with a REST API can be a real pain: you have to handle many aspects, such as making connections, caching, retrying failed requests, threading, response parsing, error handling, and more. Retrofit, on the other hand, is a well-planned, documented and tested library that will save you a lot of precious time and headaches.
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'// compulsory
compile 'com.squareup.retrofit2:converter-gson:2.1.0' //for retrofit conversion
First, add this lines to gradle file
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup:otto:1.3.8'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
Then Create Objects in OnCreate of Activity
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client= new OkHttpClient
.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.addInterceptor(interceptor).build();
Gson gson=new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
Retrofit retrofit= new Retrofit.Builder()
.baseUrl("url")
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
Create an iterface
public interface summaryListAPI {
//post
#FormUrlEncoded
#POST("index.php")
Call<summaryList> post(
#Field("status") String status,
#Field("sox") String sox
);
//get
#GET("yesbdeChatHistoryList/{userId}/")
Call<List<ChatTabTwoResp>> getFriends(
#Path("userId") int userId
);
}
Create classes
public class summaryList {
#SerializedName("bookingSummary") #Expose private List<summaryListData> status = new ArrayList<summaryListData>();
}
public class summaryListData {
#SerializedName("date") #Expose private String date;
}
Add this Method to your activity
public void apiSummaryListMain(final Retrofit retrofit) {
retrofit.create(summaryListAPI.class).post("8547861657","100").enqueue(new Callback<summaryList>() {
#Override
public void onResponse(Call<summaryList> call, Response<summaryList> response) {
if (response.isSuccessful()) {
progressBar.setVisibility(View.INVISIBLE);
List<summaryListData> summary_List= response.body().getStatus();
}else{
}
}
#Override
public void onFailure(Call<summaryList> call, Throwable t) {
}
});
}
Its Working
package com.keshav.gmailretrofitexampleworking.network;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ApiClient {
public static final String BASE_URL = "http://api.androidhive.info/json/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
==============================================
package com.keshav.gmailretrofitexampleworking.network;
import com.keshav.gmailretrofitexampleworking.models.Message;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
public interface ApiInterface {
#GET("inbox.json")
Call<List<Message>> getInbox();
}
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
=====================================================
Call Retrofit 2 APi inside onCreate
private void getInbox() {
swipeRefreshLayout.setRefreshing(true);
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<List<Message>> call = apiService.getInbox();
call.enqueue(new Callback<List<Message>>() {
#Override
public void onResponse(Call<List<Message>> call, Response<List<Message>> response) {
// clear the inbox
messages.clear();
// add all the messages
// messages.addAll(response.body());
// TODO - avoid looping
// the loop was performed to add colors to each message
Log.e("keshav","response" +response.body());
for (Message message : response.body()) {
// generate a random color
// TODO keshav Generate Random Color Here
message.setColor(getRandomMaterialColor("400"));
messages.add(message);
}
mAdapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
#Override
public void onFailure(Call<List<Message>> call, Throwable t) {
Toast.makeText(getApplicationContext(), "Unable to fetch json: " + t.getMessage(), Toast.LENGTH_LONG).show();
swipeRefreshLayout.setRefreshing(false);
}
});
}
Source Code
https://drive.google.com/open?id=0BzBKpZ4nzNzUVFRnVVkzc0JabUU
https://drive.google.com/open?id=0BzBKpZ4nzNzUc2FBdW00WkRfWW8
I just braked this problem in a very easy way you just need install a plugin and follow some steps to implement retrofit in any of your App.:
Already posted answer : Retrofit in android?
Add (QAssist - Android Studio Plugin) Android plugin in your Android studio. ( https://github.com/sakkeerhussain/QAssist ).
Hope this will help you.
Simple retrofit + okhttp integration using RxJava
public WebService apiService(Context context) {
String mBaseUrl = context.getString(BuildConfig.DEBUG ? R.string.local_url : R.string.live_url);
int cacheSize = 5 * 1024 * 1024; // 5 MB
Cache cache = new Cache(context.getCacheDir(), cacheSize);
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(120, TimeUnit.SECONDS)
.writeTimeout(120, TimeUnit.SECONDS)
.connectTimeout(120, TimeUnit.SECONDS)
.addInterceptor(loggingInterceptor)
//.addNetworkInterceptor(networkInterceptor)
.cache(cache)
.build();
return new Retrofit.Builder().baseUrl(mBaseUrl)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build().create(WebService.class);
}
public interface APIService {
#POST(Constant.updateProfile)
#FormUrlEncoded
Call<ResponseBody> updateProfile(
#Field("user_id") String user_id,
#Field("first_name") String first_name,
#Field("last_name") String last_name
);
}
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
public class Body {
// Check Status if Status True or False
String status;
String message;
String checksum;
}
public interface OnBodyResponseListner {
public void onSucces(Body response);
public void onFailure(Body response);
public void onBlankBody(Call<ResponseBody> call);
}
public static void setOnWebServiceCallListner(final Call<ResponseBody> t, final OnBodyResponseListner onBodyResponseListner) {
t.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
call.cancel();
Gson gson = new GsonBuilder().serializeNulls().create();
String json = response.body().string();
Log.d(TAG, json + " ~ Response ~ " + json);
Body body = gson.fromJson(json, Body.class);
if (body.getStatus().equalsIgnoreCase("true")) {
onBodyResponseListner.onSucces(body);
} else {
onBodyResponseListner.onFailure(body);
}
} catch (Exception e) {
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
onBodyResponseListner.onBlankBody(call);
Log.d(TAG, "~ Response Message Blank ~ " + t.getMessage() + " \n Localize Message ~ " + t.getLocalizedMessage() + " \n" + t.getStackTrace().toString());
}
});
}
APIService mService = RetrofitClient.getClient(Constant.BASE_URL).create(APIService.class);
Oprations.setOnWebServiceCallListner(mService.updateProfile("12",
"first_name",
"last,name"
), new OnBodyResponseListner() {
#Override
public void onSucces(Body response) {
}
#Override
public void onFailure(Body response) {
Toast.makeText(mContext, response.getMessage(), Toast.LENGTH_SHORT).show();
}
#Override
public void onBlankBody(Call<ResponseBody> call) {
}
});
}
First, add the dependency - compile 'com.squareup.retrofit:retrofit:1.7.1'
Create retrofit instance class
public class RetrofitClientInstance {
private Context context;
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit retrofit
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(BuildConfig.SERVER_URL)
.client(getRequestHeader())
.addConverterFactory(GsonConverterFactory.create());
public static HttpLoggingInterceptor setLogger() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
return logging;
}
public static <S> S createService(Class<S> serviceClass) {
if (!httpClient.interceptors().isEmpty()) {
httpClient.interceptors().clear();
}
httpClient.authenticator(new AccessTokenAuthenticator());
httpClient.readTimeout(60,TimeUnit.SECONDS);
httpClient.connectTimeout(60,TimeUnit.SECONDS);
httpClient.addInterceptor(setLogger());
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.header("LocalSystemDate", MyApplication.getInstance().getCurrentDateAndTimeWithTimeZone())
.addHeader("channel_id", AppConst.CHANNEL_ID)
.addHeader("Authorization", "Bearer" + " " + SharedPref.getsAccessToken())
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
OkHttpClient client = httpClient.build();
Retrofit retrofit = builder.client(client).build();
return retrofit.create(serviceClass);
}
private static OkHttpClient getRequestHeader() {
return new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.build();
}
}
Write the interface
public interface GetDataService {
#Headers("Content-Type: application/json")
#POST("login")
Call<LoginResponseModel> loginUser(
#Body LoginBodyModel loginBodyModel
);
}
Call the service
GetDataService service = RetrofitClientInstance.createService(GetDataService.class);
Call<LoginResponseModel> loginModelCall = service.loginUser(loginBodyModel);
loginModelCall.enqueue(new Callback<LoginResponseModel>() {
#Override
public void onResponse(Call<LoginResponseModel> call, Response<LoginResponseModel> response) {
}
#Override
public void onFailure(Call<LoginResponseModel> call, Throwable t) {
}
});
You can do this with hilt
#Module
#InstallIn(SingletonComponent::class)
object RestClientModule {
#Provides
#Singleton
internal fun provideApiService(
#WeatherRetrofit retrofit: Retrofit
): ApiService = retrofit.create(ApiService::class.java)
#Provides
#WeatherRetrofit
#Singleton
internal fun provideHiCityRetrofit(
okHttpClient: OkHttpClient,
moshi: Moshi
): Retrofit = Retrofit.Builder()
.baseUrl(EndPoint.STAGE_BASE_URL)
.client(okHttpClient)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
}
You can checkout this Github Link with source-code avaible for login and signup API in android. https://github.com/probelalkhan/kotlin-retrofit-tutorial/commits/master
Or you can check this tutorial for learning purpose.
https://youtu.be/TyJEDhauUeQ
Or for more other details checkout this
https://gist.github.com/codinginflow/d7a02bd69eebf566b4650c41bc362be7

Categories

Resources