I'm trying to get data from http://www.gibdd.ru/proxy/check/fines/2.0/client.php, but server responds that captcha is incorrect or expired. In advanced rest client into chrome request work's perfect. My alghoritm to getting data is:
Get session from http://www.gibdd.ru/proxy/check/getSession.php
Get captcha with session id http://www.gibdd.ru/proxy/check/getCaptcha.php?PHPSESSID=te67jgdiv53v956fcv8rk9mg81
And then send form data to http://www.gibdd.ru/proxy/check/fines/2.0/client.php
I think my problem with cookies, i set cookies = sessionId, like rest client, but something gone wrong
UPD: I'm using retrofit to server requests
That API class
private static final String URL= "http://www.gibdd.ru";
private static RestAdapter restAdapter;
public interface IGibdd {
#GET("/proxy/check/getSession.php")
void getSession(Callback<Session> callback);;
#FormUrlEncoded
#POST("/proxy/check/fines/2.0/client.php")
void getFines(#Field("regnum") String regnum,
#Field("regreg") String regreg,
#Field("stsnum") String stsnum,
#Field("req") String reqfines,
#Field("captchaWord") String captchaWord,
Callback<Answer> callback);
}
This method requesting captcha, after getting session id
private void getCaptcha() {
final API.IGibdd iGibdd = API.getRestAdapter(this).create(API.IGibdd.class);
iGibdd.getSession(new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
if (response.getStatus() != 200) {
getCaptcha();
} else {
String cookie = API.loadCookies(CheckFinesActivity.this);
url = getString(R.string.captcha_url) + cookie + "&" + new Date().getTime();
HashMap<String, String> map = new HashMap<String, String>();
map.put("Cookie", cookie);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.extraForDownloader(map)
.build();
ImageLoaderConfiguration conf = new ImageLoaderConfiguration.Builder(CheckFinesActivity.this)
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(conf);
imageLoader.displayImage(url, mCaptchaImage);
}
}
#Override
public void failure(RetrofitError error) {
error.printStackTrace();
}
});
}
And then, after entering captcha code, i call this method
String reqfines = "fines:" + mCarNumber.getText().toString() + ":" + mCarRegion.getText().toString() + ":" + mDocNumber.getText().toString();
iGibdd.getFines(mCarNumber.getText().toString(),
mCarRegion.getText().toString(),
mDocNumber.getText().toString(),
reqfines,
mCaptcha.getText().toString(),
new Callback<Answer>() {
#Override
public void success(Answer s, Response response) {
Toast.makeText(CheckFinesActivity.this, "Success", Toast.LENGTH_LONG).show();
API.clearSP(CheckFinesActivity.this);
getCaptcha();
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(CheckFinesActivity.this, "Error", Toast.LENGTH_LONG).show();
}
});
}
});
UPD2:
Problem is solved. I recreated OkHttp client for a new request and it clears current session
Related
I am trying to implement server side using php Joomla API for my application. User sends login info and server processes and creates session successfully. However, i am unable to catch this session data in android. I am using volley to perform the post, however multiple post seems to create new logins which should not be the case as user is already logged in. I am guessing their is a problem with headers being sent by volley. Anyone with a solution for this i will appreciate.
Note server side is working 100%. Problem is only with android.
protected void doLogin(){
final String username = editTextUsername.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
final CookieManager cookieManager = new CookieManager(new PersistentCookieStore(getApplicationContext()), CookiePolicy.ACCEPT_ORIGINAL_SERVER);
CookieHandler.setDefault(cookieManager);
RequestQueue queue = Volley.newRequestQueue(this);
String loginUrl ="http://loginurl/sesslogin/";
final StringRequest stringRequest = new StringRequest(Request.Method.POST, loginUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//COOKIE_JAR = cookieManager.getCookieStore().getCookies().toString();
//PersistentCookieStore.getCookies();
// Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
//stringRequest.getHeaders().values()
Toast.makeText(getApplicationContext(), response , Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "That didn't work!", Toast.LENGTH_LONG).show();
}
}
){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_USERNAME,username);
params.put(KEY_PASSWORD,password);
return params;
}
};
queue.add(stringRequest);
}
I also got an implementation of shared preference and cookie manager that i found on Github and is part of my code. But i dont see any impact of this code.
public class PersistentCookieStore implements CookieStore {
/**
* The default preferences string.
*/
private final static String PREF_DEFAULT_STRING = "";
/**
* The preferences name.
*/
private final static String PREFS_NAME = PersistentCookieStore.class.getName();
/**
* The preferences session cookie key.
*/
private final static String PREF_SESSION_COOKIE = "Set-Cookie";
private CookieStore mStore;
private Context mContext;
/**
* #param context The application context
*/
public PersistentCookieStore(Context context) {
// prevent context leaking by getting the application context
mContext = context.getApplicationContext();
// get the default in memory store and if there is a cookie stored in shared preferences,
// we added it to the cookie store
mStore = new CookieManager().getCookieStore();
String jsonSessionCookie = getJsonSessionCookieString();
if (!jsonSessionCookie.equals(PREF_DEFAULT_STRING)) {
Gson gson = new Gson();
HttpCookie cookie = gson.fromJson(jsonSessionCookie, HttpCookie.class);
mStore.add(URI.create(cookie.getDomain()), cookie);
}
}
#Override
public void add(URI uri, HttpCookie cookie) {
if (cookie.getName().equals("sessionid")) {
// if the cookie that the cookie store attempt to add is a session cookie,
// we remove the older cookie and save the new one in shared preferences
remove(URI.create(cookie.getDomain()), cookie);
saveSessionCookie(cookie);
}
mStore.add(URI.create(cookie.getDomain()), cookie);
}
#Override
public List<HttpCookie> get(URI uri) {
return mStore.get(uri);
}
#Override
public List<HttpCookie> getCookies() {
return mStore.getCookies();
}
#Override
public List<URI> getURIs() {
return mStore.getURIs();
}
#Override
public boolean remove(URI uri, HttpCookie cookie) {
return mStore.remove(uri, cookie);
}
#Override
public boolean removeAll() {
return mStore.removeAll();
}
private String getJsonSessionCookieString() {
return getPrefs().getString(PREF_SESSION_COOKIE, PREF_DEFAULT_STRING);
}
/**
* Saves the HttpCookie to SharedPreferences as a json string.
*
* #param cookie The cookie to save in SharedPreferences.
*/
private void saveSessionCookie(HttpCookie cookie) {
Gson gson = new Gson();
String jsonSessionCookieString = gson.toJson(cookie);
SharedPreferences.Editor editor = getPrefs().edit();
editor.putString(PREF_SESSION_COOKIE, jsonSessionCookieString);
editor.apply();
}
private SharedPreferences getPrefs() {
return mContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
}
}
I have identified the issue. So i will answer this for anyone encountering the same problem. The problem was here;
final CookieManager cookieManager = new CookieManager(new PersistentCookieStore(getApplicationContext()), CookiePolicy.ACCEPT_ORIGINAL_SERVER);
CookieHandler.setDefault(cookieManager);
This CookieManager for some reason should be instatiated during the onCreate method. Also the type final is unnecesary here. My final code is as follows;
#Override
protected void onCreate(Bundle savedInstanceState) {
//INSTANTIATE COOKIE MANAGER
CookieManager cookieManager = new CookieManager(new PersistentCookieStore(this.getApplicationContext()), CookiePolicy.ACCEPT_ORIGINAL_SERVER);
CookieHandler.setDefault(cookieManager);
doLogin();
}
In this where I used to Book Class to store my response. Instead of this class I would like to add multiple services. Please let me know how to use this kind situation.
private void getBooks() {
//While the app fetched data we are displaying a progress dialog
final ProgressDialog loading = ProgressDialog.show(this, "Fetching Data", "Please wait...", false, false);
final String authorizationString = "Basic " + Base64.encodeToString(
("#username" + ":" + "#password").getBytes(),
Base64.NO_WRAP);
RequestInterceptor requestInterceptor = new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
request.addHeader("Authorization", authorizationString);
}
};
//Creating a rest adapter
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(ROOT_URL)
.setRequestInterceptor(requestInterceptor)
.build();
//Creating an object of our api interface
BooksAPI api = adapter.create(BooksAPI.class);
api.createUser(user, new Callback<Book>() {
#Override
public void success(Book book, Response response) {
loading.dismiss();
Log.i("s", "s");
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
_time.append("\n Time After service :" + currentDateandTime);
Toast.makeText(context, "", Toast.LENGTH_SHORT).show();
}
#Override
public void failure(RetrofitError error) {
loading.dismiss();
Log.i("s", "etr");
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
You can put your common code in any singleton class like application. Assuming your base url will be same so no need to create different service class like BookAPI but crate a single service file and put your all api there. Common code :-
RequestInterceptor requestInterceptor = new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
request.addHeader("Authorization", authorizationString);
}
};
//Creating a rest adapter
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(ROOT_URL)
.setRequestInterceptor(requestInterceptor)
.build();
//Creating an object of our api interface
BooksAPI api = adapter.create(BooksAPI.class);
BooksAPI api can be moved to class level and you can access it from activities by public method.
This Android app is using Android Studio. The function is to scan and display data from the beacon/eddystone. The app already functions and after the scanning stops, the data saves to the local file. I need to transfer the data to the server. How can i insert the volley coding to the mainacitivity.java. I tried to put under the stopscanning button, but it shows error. Im really beginners to learn about android studio.
Here is the coding:
private void stopScanning(Button scanButton) {
try {
beaconManager.stopRangingBeaconsInRegion(region);
} catch (RemoteException e) {
// TODO - OK, what now then?
}
String scanData = logString.toString();
if (scanData.length() > 0)
{
public class MainActivity extends AppCompatActivity {
//The values of these variables will be fetched by the file(Where you will store data)
private String PREFERENCE_SCANINTERVAL = "scanInterval";
private String PREFERENCE_TIMESTAMP = "timestamp";
private String PREFERENCE_POWER = "power";
private String PREFERENCE_PROXIMITY = "proximity";
private String PREFERENCE_RSSI = "rssi";
private String PREFERENCE_MAJORMINOR = "majorMinor";
private String PREFERENCE_UUID = "uuid";
private String PREFERENCE_INDEX = "index";
private String PREFERENCE_LOCATION = "location";
private String PREFERENCE_REALTIME = "realTimeLog";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "http://beaconscanner.byethost33.com/beaconscanner.php";//This is the url of your server where you will be sending the data to.
//StringRequest is a class in the Volley Library.
//The constructor of this class has four parameters.
// 1 parameter is Request.Method.POST =this specifies the method type, That is post.
//2 parameter is the url you will be sending the request to.That is the server
//3 parameter is the response listener , It will listen for any response from your server . you will be able to fetch the response from the server using this.
//4 parameter is the error listener, it will listen for any error's during the connection or etc.
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Here you will be able to fetch the response coming from the server.
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
//This is the method we override.
{
//This is method is used to send the data to the server for post methods. This method returns all the data you want to send to server. This is how you send data using Volley.
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("scanInterval",PREFERENCE_SCANINTERVAL);
params.put("timestamp",PREFERENCE_SCANINTERVAL);
params.put("power",PREFERENCE_POWER);
params.put("proximity",PREFERENCE_PROXIMITY);
params.put("rssi",PREFERENCE_RSSI);
params.put("majorMinor",PREFERENCE_MAJORMINOR);
params.put("uuid",PREFERENCE_UUID);
params.put("index",PREFERENCE_INDEX);
params.put("location",PREFERENCE_LOCATION);
params.put("realTimelog",PREFERENCE_REALTIME);
return params;
}
};//The constructor ends here.
Volley.newRequestQueue(this).add(request);// This is the main potion of this code. if you dont add this you will not be able to send the request to your server. this helps you to send it.
}
}
// Write file
fileHelper.createFile(scanData);
// Display file created message.
Toast.makeText(getBaseContext(),
"File saved to:" + getFilesDir().getAbsolutePath(),
Toast.LENGTH_SHORT).show();
scanButton.setText(MODE_STOPPED);
} else {
// We didn't get any data, so there's no point writing an empty file.
Toast.makeText(getBaseContext(),
"No data captured during scan, output file will not be created.",
Toast.LENGTH_SHORT).show();
scanButton.setText(MODE_STOPPED);
}
}
Please add your stacktrace. Also I guess that you want to send the data using the body not the params :). In that case, call the request using the following signature:
new JsonObjectRequest(Request.Method.POST, url, new JSONObject(bodyData), new Response.Listener<JSONObject>() { }
public void sendMyData(HashMap map) {
String url = "http://"....";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressBar.setVisibility(View.INVISIBLE);
try {// to receive server response, in this example it's jsonArray
JSONArray jsonArray = new JSONArray(response);
//code
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
}) {
#Override
public String getBodyContentType() { // if your server uses java restfull webservice , you have to override this content type
return "application/json";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {// parameters which should server receive
Map<String, String> parameters =map;
return parameters;
}
};
requestQueue.add(request);
}
trying to perform POST request using Retrofit library. Doing everything as usual:
interface ApiCallHelper {
#POST("/")
void save(#Body HashMap<String, Object> params, Callback<Response> callBack);
}
then call the following method:
public void menuSaveClicked(){
String url = SharedData.BASE_URL +
"api/v1/vendors/update_profile.json";
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("userId", mPrefs.getUserId());
params.put("accessToken",mPrefs.getToken());
params.put("phone", aq.id(R.id.etBusinessPhone).getText());
params.put("address", aq.id(R.id.etBusinessAddress).getText());
params.put("name", aq.id(R.id.etBusinessContactName).getText());
params.put("businessName", aq.id(R.id.etBusinessName).getText());
params.put("registrationNumber", aq.id(R.id.etBusinessRegNumber).getText());
params.put("serviceTypeIds",serviceTypeIds );
params.put("serviceAreaIds",serviceAreaIds );
params.put("website",aq.id(R.id.etBusinessWebsite).getText() );
params.put("facebook",aq.id(R.id.etBusinessFacebook).getText() );
params.put("postcode",aq.id(R.id.etBusinessPostCode).getText() );
params.put("state_id",currentState.getId() );
params.put("city_id",currentCity.getId() );
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(url)
.build();
ApiCallHelper apiCallHelper = restAdapter.create(ApiCallHelper.class);
mPD.show();
apiCallHelper.save(params, new Callback<Response>() {
#Override
public void success(Response object, Response response) {
if (mPD != null)
mPD.hide();
Toast.makeText(mContext, "Updated successfully", Toast.LENGTH_SHORT).show();
}
#Override
public void failure(RetrofitError error) {
if (mPD != null)
mPD.hide();
}
});
}
So the problem is that the call is very slow around 5-7 mins and then I get "java.lang.StackOverflowError: stack size 1036KB" error.
Tried using AQuery for the same api - works fine (The reason why I don't want use it, is because AQuery sends all arrays as a single String; my api can't accept it)
There are two ways to make a Retrofit call synchronous (with methods, returning values) and asynchronous (with callbacks).
Second one, async, works great out-of-the-box. But there is an issue, when it comes to OAuth2 authenticated access.
Can you recommend me a good RestAdapter, compatible with asynchronous retrofit calls.
I tried to use interceptors as follows, but it makes network calls on the main thread, which is not sufficient to me (Android). I am trying to use the following code (not mine).
public class SecuredRestBuilder extends RestAdapter.Builder {
private class OAuthHandler implements RequestInterceptor {
private boolean loggedIn;
private Client client;
private String tokenIssuingEndpoint;
private String username;
private String password;
private String clientId;
private String clientSecret;
private String accessToken;
public OAuthHandler(Client client, String tokenIssuingEndpoint, String username,
String password, String clientId, String clientSecret) {
super();
this.client = client;
this.tokenIssuingEndpoint = tokenIssuingEndpoint;
this.username = username;
this.password = password;
this.clientId = clientId;
this.clientSecret = clientSecret;
}
/**
* Every time a method on the client interface is invoked, this method is
* going to get called. The method checks if the client has previously obtained
* an OAuth 2.0 bearer token. If not, the method obtains the bearer token by
* sending a password grant request to the server.
*
* Once this method has obtained a bearer token, all future invocations will
* automatically insert the bearer token as the "Authorization" header in
* outgoing HTTP requests.
*
*/
#Override
public void intercept(RequestFacade request) {
// If we're not logged in, login and store the authentication token.
if (!loggedIn) {
try {
// This code below programmatically builds an OAuth 2.0 password
// grant request and sends it to the server.
// Encode the username and password into the body of the request.
FormUrlEncodedTypedOutput to = new FormUrlEncodedTypedOutput();
to.addField("username", username);
to.addField("password", password);
// Add the client ID and client secret to the body of the request.
to.addField("client_id", clientId);
to.addField("client_secret", clientSecret);
// Indicate that we're using the OAuth Password Grant Flow
// by adding grant_type=password to the body
to.addField("grant_type", "password");
// The password grant requires BASIC authentication of the client.
// In order to do BASIC authentication, we need to concatenate the
// client_id and client_secret values together with a colon and then
// Base64 encode them. The final value is added to the request as
// the "Authorization" header and the value is set to "Basic "
// concatenated with the Base64 client_id:client_secret value described
// above.
String base64Auth = BaseEncoding.base64().encode(new String(clientId + ":" + clientSecret).getBytes());
// Add the basic authorization header
List<Header> headers = new ArrayList<Header>();
headers.add(new Header("Authorization", "Basic " + base64Auth));
// Create the actual password grant request using the data above
Request req = new Request("POST", tokenIssuingEndpoint, headers, to);
// Request the password grant.
Response resp = client.execute(req);
// Make sure the server responded with 200 OK
if (resp.getStatus() < 200 || resp.getStatus() > 299) {
// If not, we probably have bad credentials
throw new SecuredRestException("Login failure: "
+ resp.getStatus() + " - " + resp.getReason());
} else {
// Extract the string body from the response
String body = IOUtils.toString(resp.getBody().in());
// Extract the access_token (bearer token) from the response so that we
// can add it to future requests.
accessToken = new Gson().fromJson(body, JsonObject.class).get("access_token").getAsString();
// Add the access_token to this request as the "Authorization"
// header.
request.addHeader("Authorization", "Bearer " + accessToken);
// Let future calls know we've already fetched the access token
loggedIn = true;
}
} catch (Exception e) {
throw new SecuredRestException(e);
}
}
else {
// Add the access_token that we previously obtained to this request as
// the "Authorization" header.
request.addHeader("Authorization", "Bearer " + accessToken );
}
}
private String username;
private String password;
private String loginUrl;
private String clientId;
private String clientSecret = "";
private Client client;
#Override
public RestAdapter build() {
if (username == null || password == null) {
throw new SecuredRestException(
"You must specify both a username and password for a "
+ "SecuredRestBuilder before calling the build() method.");
}
if (client == null) {
client = new OkClient();
}
OAuthHandler hdlr = new OAuthHandler(client, loginUrl, username, password, clientId, clientSecret);
setRequestInterceptor(hdlr);
return super.build();
}
// setters and getters here
}
So, I ended up splitting RestAdapter class into two separate classes. The first one gets token. Another one is a RestAdapter class that takes the token as input.
Class for getting token:
public class GetTokenRequest {
public static final String TAG = GetTokenRequest.class.getCanonicalName();
public static final String CLIENT_ID = AccessPoint.CLIENT_ID;
public static final String CLIENT_SECRET = AccessPoint.CLIENT_SECRET;
public static final String ENDPOINT = AccessPoint.ENDPOINT;
public static final String TOKEN_PATH = AccessPoint.TOKEN_PATH;
public interface Listener {
void onGetTokenSucess(String token);
void onGetTokenUnauthorized();
void onGetTokenFailure();
}
public static void getAccessToken(Client client, String username, String password,
final Listener callback) {
try {
// This code below programmatically builds an OAuth 2.0 password
// grant request and sends it to the server.
// Encode the username and password into the body of the request.
FormUrlEncodedTypedOutput to = new FormUrlEncodedTypedOutput();
to.addField("username", username);
to.addField("password", password);
// Add the client ID and client secret to the body of the request.
to.addField("client_id", CLIENT_ID);
to.addField("client_secret", CLIENT_SECRET);
// Indicate that we're using the OAuth Password Grant Flow
// by adding grant_type=password to the body
to.addField("grant_type", "password");
// The password grant requires BASIC authentication of the client.
// In order to do BASIC authentication, we need to concatenate the
// client_id and client_secret values together with a colon and then
// Base64 encode them. The final value is added to the request as
// the "Authorization" header and the value is set to "Basic "
// concatenated with the Base64 client_id:client_secret value described
// above.
String base64Auth = BaseEncoding.base64()
.encode(new String(CLIENT_ID + ":" + CLIENT_SECRET).getBytes());
// Add the basic authorization header
List<Header> headers = new ArrayList<Header>();
headers.add(new Header("Authorization", "Basic " + base64Auth));
// Create the actual password grant request using the data above
Request req = new Request("POST", ENDPOINT + TOKEN_PATH, headers, to);
// Request the password grant.
Response resp = client.execute(req);
if (resp == null) {
Log.e(TAG, "resp is null");
callback.onGetTokenFailure();
return;
}
int status = resp.getStatus();
// Make sure the server responded with 200 OK
if (status >= 200 && status < 300) {
Log.e(TAG, "getToken response code is okay");
// Extract the string body from the response
final String body = IOUtils.toString(resp.getBody().in());
// Extract the access_token (bearer token) from the response so that we
// can add it to future requests.
if (callback instanceof LoginActivity)
((LoginActivity) callback).runOnUiThread(new Runnable() {
#Override
public void run() {
callback.onGetTokenSucess(new Gson().fromJson(body, JsonObject.class)
.get("access_token").getAsString());
}
});
} else if (status == HttpStatus.SC_UNAUTHORIZED
|| status == HttpStatus.SC_BAD_REQUEST) {
Log.e(TAG, "getToken response code is 401");
// Incorrect credentials
if (callback instanceof LoginActivity)
((LoginActivity) callback).runOnUiThread(new Runnable() {
#Override
public void run() {
callback.onGetTokenUnauthorized();
}
});
} else {
// Other error
Log.e(TAG, "getToken response code - other");
if (callback instanceof LoginActivity)
((LoginActivity) callback).runOnUiThread(new Runnable() {
#Override
public void run() {
((LoginActivity) callback).onGetTokenFailure();
}
});
}
} catch (Exception e) {
Log.e(TAG, "Exception caught");
Log.e(TAG, e.toString());
if (callback instanceof LoginActivity)
((LoginActivity) callback).runOnUiThread(new Runnable() {
#Override
public void run() {
callback.onGetTokenFailure();
}
});
}
}
}
RestAdapter class:
public class SecuredRestAdapter extends RestAdapter.Builder {
private class OAuthHandler implements RequestInterceptor {
private boolean loggedIn;
private Client client;
private String tokenIssuingEndpoint;
private String username;
private String password;
private String clientId;
private String clientSecret;
private String accessToken;
public OAuthHandler(Client client, String accessToken) {
super();
this.client = client;
this.accessToken = accessToken;
}
#Override
public void intercept(RequestFacade request) {
// Add the access_token that we previously obtained to this request as
// the "Authorization" header.
request.addHeader("Authorization", "Bearer " + accessToken);
}
}
private String loginUrl;
private Client client;
private String token;
public SecuredRestAdapter setLoginEndpoint(String endpoint){
loginUrl = endpoint;
return this;
}
#Override
public SecuredRestAdapter setEndpoint(String endpoint) {
return (SecuredRestAdapter) super.setEndpoint(endpoint);
}
#Override
public SecuredRestAdapter setEndpoint(Endpoint endpoint) {
return (SecuredRestAdapter) super.setEndpoint(endpoint);
}
#Override
public SecuredRestAdapter setClient(Client client) {
this.client = client;
return (SecuredRestAdapter) super.setClient(client);
}
#Override
public SecuredRestAdapter setClient(Provider clientProvider) {
client = clientProvider.get();
return (SecuredRestAdapter) super.setClient(clientProvider);
}
#Override
public SecuredRestAdapter setErrorHandler(ErrorHandler errorHandler) {
return (SecuredRestAdapter) super.setErrorHandler(errorHandler);
}
#Override
public SecuredRestAdapter setExecutors(Executor httpExecutor,
Executor callbackExecutor) {
return (SecuredRestAdapter) super.setExecutors(httpExecutor,
callbackExecutor);
}
#Override
public SecuredRestAdapter setRequestInterceptor(
RequestInterceptor requestInterceptor) {
return (SecuredRestAdapter) super
.setRequestInterceptor(requestInterceptor);
}
#Override
public SecuredRestAdapter setConverter(Converter converter) {
return (SecuredRestAdapter) super.setConverter(converter);
}
#Override
public SecuredRestAdapter setProfiler(#SuppressWarnings("rawtypes") Profiler profiler) {
return (SecuredRestAdapter) super.setProfiler(profiler);
}
#Override
public SecuredRestAdapter setLog(Log log) {
return (SecuredRestAdapter) super.setLog(log);
}
#Override
public SecuredRestAdapter setLogLevel(LogLevel logLevel) {
return (SecuredRestAdapter) super.setLogLevel(logLevel);
}
public SecuredRestAdapter setToken(String token) {
this.token = token;
return this;
}
#Override
public RestAdapter build() {
if (this.token == null || this.token.equals(""))
throw new SecuredRestAdapterException(
"Token must be provided, when calling SecuredRestAdapter");
if (client == null) {
client = new OkClient();
}
OAuthHandler hdlr = new OAuthHandler(client, token);
setRequestInterceptor(hdlr);
return super.build();
}
}
Exception class:
public class SecuredRestAdapterException extends RuntimeException {
public SecuredRestAdapterException(String message) {
super(message);
}
}