How to keep session alive? Android library Ion - android

I'm developing an android app that uses Ion library for requesting API data.
Here is how I'm requesting
void getData(final OnDbData listener) {
Ion.with(context)
.load(BASE_URL + url)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject jsonObject) {
if (e == null) {
listener.OnDbDataReceived(jsonObject, false);
} else {
Log.d("DBDATA-IonDB", e.getMessage() + "");
listener.OnDbDataReceived(jsonObject, true);
}
}
});
}
I'm successfully login in to my application but when I send request for other data Ion library is opening new connection and API is returning UNAUTHORIZED error. From the server side the session time out is set to 2 hours. One more thing that is confusing me is that when I use my local server (API in my computer) it is working correctly but when I connect to remote server It is being disconnected. If you know how to handle this please help!

Related

how to change this code android for to verify the connection

I am a beginner in android development, looking for how to make it verifiable code for server connection, ie if the user does not have a connection, and it connects to my server, in this case an error message will show "connection error" or nothing affair.
thank you for helping me :)
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File f = new File(path);
Future uploading = Ion.with(MainActivity.this)
.load("http://x.x.x.x/upload_file") //->how to change this code for to verify the connection
.setMultipartFile("image",f)
//asJsonObject()
.asString()
.withResponse()
.setCallback(new FutureCallback<Response<String>>() {
#Override
public void onCompleted(Exception e, Response<String> result) {
try {
JSONObject jobj = new JSONObject(result.getResult());
Toast.makeText(getApplicationContext(), jobj.getString("response"), Toast.LENGTH_SHORT).show();
} catch (JSONException e1) {
e1.printStackTrace();
}
}
});
}
});
Based on the information you provided, I suggest you refer to this answer. It shows you how to check if the device is connected to the internet.
After checking if a connection is available or not, you can continue normally, or display an alert message (i.e. via Toast or Snackbar) to inform the user that no connection can be made.
Hope this helps.

Why is Retrofit responding with 404 error code?

I have written a Retrofit code which has a Yii2 backend. The problem is: when I call the web-service on backend, it works perfectly. However, when I try to call the web-service from android device; it throws a response code of 404. Here is what I have done:
I am targeting a url which looks like: http://192.168.0.104/root-web/web/index.php?r= and it had an end-point: root/register
public interface RegisterAPIService {
#POST("practice/register")
Call<RegisterModel> registerUser(#Body RegisterDetails registerDetails);
}
The code in my activity looks like this..
RegisterDetails registerDetails = new RegisterDetails(email, mobile, password);
RegisterAPIService registerAPIService = retrofit.create(RegisterAPIService.class);
Call<RegisterModel> call =registerAPIService.registerUser(registerDetails);
call.enqueue(new Callback<RegisterModel>() {
#Override
public void onResponse(Response<RegisterModel> response) {
Log.d("Message", "code..."+response.code() + " message..." + response.message()+" body..."+response.body());
}
#Override
public void onFailure(Throwable t) {
}
});
} else {
// Error
}
}
I am getting 404 for the above code. I am trying to send my parameters in the form of a POST request. Please guide me through it.
You should call your development machine from the device, by its ip address, based on how they are connected. Also you can use Android Reverse Tethering tools for your operating system. for further study and options you can take a look at the answers to this question

Ion Android getHeaders

How do I get a specific header using the Ion network library for Android?
This is what I'm trying:
...
.setCallback(new FutureCallback<Response<String>>() {
#Override
public void onCompleted(Exception e, Response<String> result) {
System.out.println("header: " + result.getHeaders().message("mykey"));
}
});
message(String) sets the HTTP response message. I should make that internal to avoid confusion.
Use
getHeaders().getHeaders().get(String)
It's a bit obtuse at the moment, will need to clean that API up in the next release.

RetrofitError response is null on Android 4.2.2

I'm using Retrofit library in my Android project. I have a rest server and trying to make request to it's login method. If login failed, server returns me 401 error and detailed message in json. My problem is that on my Nexus 5 with Android 5.0 it works fine, I can get the response body from the RetrofitError object. But on other devices, such as Sony Xperia M with Android 4.2.2 on the same request I'm getting No authentication challenges found exception and the RetrofitError.response object is null. Any ideas?
UPDATE
Here is my code. I also use Robospice library.
So this is an interface:
#POST("/auth")
User logIn(#Body UserSignUp userSignUp);
Here is my Robospice request class
public class UserLoginRequest extends RetrofitSpiceRequest<User, Server> {
private UserSignUp userSignUp;
public UserLoginRequest(UserSignUp userSignUp) {
super(User.class, Server.class);
this.userSignUp = userSignUp;
}
#Override
public User loadDataFromNetwork() throws Exception {
return getService().logIn(userSignUp);
}
}
And here is my request listener:
public final class UserLoginListener implements RequestListener<User> {
#Override
public void onRequestFailure(SpiceException spiceException) {
if (spiceException.getCause() != null && ((RetrofitError) spiceException.getCause()).getBody() != null) {
Toast.makeText(LoginActivity.this, ((ResponseDto) (((RetrofitError) spiceException.getCause()).getBody())).error, Toast.LENGTH_LONG).show(); //On Nexus 5 with Android 5 this line works fine
} else {
Toast.makeText(LoginActivity.this, "Login failed", Toast.LENGTH_SHORT).show(); //On other devices I'm getting to this
}
}
#Override
public void onRequestSuccess(User user) {
//Some code here
}
}
User is a subclass of ResponseDto class. ResponseDto class has only one public string field called error.
Seems that this exception is versions related - it's IOException thrown by HttpURLConnection. Try to change server's behavior or handle the IOException in retrofit.
No authentication challenges found
This error happens beause the server sends a 401 (Unauthorized) but does not give a WWW-Authenticate header which is a hint for the client what to do next.
Take a look here

What is the code for getting a refreshed Facebook token in an Android app?

I am developing an Android app. With the impending deprecation of Facebook's offline_access permission I am trying to use the Graph API to extend the Facebook token.
https://graph.facebook.com/oauth/access_token?
client_id=APP_ID&
client_secret=APP_SECRET&
grant_type=fb_exchange_token&
fb_exchange_token=EXISTING_ACCESS_TOKEN
Can anyone provide detailed code that demonstrates how to implement the code above into an android app and obtain the refreshed Facebook token?
Thank you for your time.
Update Two:
Progress (I think)!
Using the full URL with the facebook request method results in the base URL being added to the the beginning of the URL
So instead of
String refreshUrl = "https://graph.facebook.com/oauth/access_token?client_id=12345678910&client_secret=abcdefghijklmnopqrstuvwxyz&grant_type=fb_exchange_token&fb_exchange_token="+currentAccessToken;
should use
String refreshUrl = "oauth/access_token?client_id=12345678910&client_secret=abcdefghijklmnopqrstuvwxyz&grant_type=fb_exchange_token&fb_exchange_token="+currentAccessToken;
However I am now getting the response {"error":{"message":"Error validating application. Invalid application ID.","type":"OAuthException","code":190}}
Update One:
Here is what I have I tried. The code completes, that is OnComplete on the listerner is called, BUT the response does not contain a new access token or expiry value.
void refreshWithGraph() {
AsyncFacebookRunner extendingAsyncRunner = new AsyncFacebookRunner(facebook);
Bundle parameters = new Bundle();
//the variable currentAccessToken is obtained after authorisation is complete using currentAccessToken = facebook.getAccessToken();
String refreshUrl = "https://graph.facebook.com/oauth/access_token?client_id=12345678910&client_secret=abcdefghijklmnopqrstuvwxyz&grant_type=fb_exchange_token&fb_exchange_token="+currentAccessToken;
extendingAsyncRunner.request(refreshUrl, parameters, new RefreshListener(), null );
}
Here is my version of RefreshListener...
//REFRESH LISTENER
public class RefreshListener extends BaseRequestListener {
public void onComplete(final String response, Object state) {
try {
final JSONObject json = Util.parseJson(response);
runOnUiThread(new Runnable() {
#Override
public void run() {
tvRefreshResponse.setText("IN REFRESH LISTENER ONCOMPLETE\nResponse is " + response);
tvRefreshToken.setText("IN REFRESH LISTENER ONCOMPLETE\nToken is " + facebook.getAccessToken());
tvRefreshExpiry.setText("IN REFRESH LISTENER ONCOMPLETE\nFacebook expiry is " + millisecToDate(facebook.getAccessExpires()));
}
}); //end runOnUiThread
} catch (JSONException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
tvRefreshResponse.setText("IN REFRESH LISTENER ONCOMPLETE CAUGHT JSON EXCEPTION \nResponse is " + response);
}
}); //end runOnUiThread
} catch (FacebookError fe) {
runOnUiThread(new Runnable() {
#Override
public void run() {
tvRefreshResponse.setText("IN REFRESH LISTENER ONCOMPLETE CAUGHT FACEBOOK ERROR \nResponse is " + response);
}
}); //end runOnUiThread
} //end catch Facebook error
} //end onComplete
#Override
public void onIOException(IOException e, Object state) {
tvRefreshResponse.setText("IN REFRESH LISTENER IOEXCEPTION \nException is "+ e.getLocalizedMessage());
}
#Override
public void onFileNotFoundException(FileNotFoundException e, Object state) {
tvRefreshResponse.setText("IN REFRESH LISTENER FILE NOT FOUND EXCEPTION \nException is "+ e.getLocalizedMessage());
}
#Override
public void onMalformedURLException(MalformedURLException e, Object state) {
tvRefreshResponse.setText("IN REFRESH MALFORMED URL \nException is "+ e.getLocalizedMessage());
}
#Override
public void onFacebookError(FacebookError e, Object state) {
tvRefreshResponse.setText("IN REFRESH ONFACEBOOK ERROR \nException is "+ e.getLocalizedMessage());
}
} //end RefreshListener
The code completes, that is OnComplete on the listerner is called, BUT the response does not contain a new access token or expiry value. The response is...
{"id":"https:\/\/graph.facebook.com\/oauth\/access_token","shares":78,"comments":1}
When I put the same URL (with a alphanumeric current token value) into a web browser the response DOES include an access token.
Related Info
Facebook's offline_access permission will be deprecated on 1st of May, 2012
Please don't suggest using the extendAccessTokenIfNeeded function in onResume() instead. I am also having trouble with that and it is the reason why I am looking into the Graph API token refreshing :-)
Related Stack Overflow Questions
Is it possible to extend Facebook tokens with extendAccessTokenIfNeeded in an Android app? (my question)
How would offline_access work after deprecation after May 1st?
Facebook access token can not be extended
Protecting app secret for extendAccessToken usage (Java/Android)
Relevant Facebook links
Facebook Android Tutorial
Facebook offline_access permission deprecation
To be honest, I'm a bit confused - looks like you have everything to get it done - and it's simple. But let me try to answer your question. Here is the code from my C# project where I extend app's token with my comments in case you are not familiar with C# languages and classes:
string currentToken = "token from somewhere";
// WebClient is used to send GET request to the given URL
// and receive the response
using (var req = new System.Net.WebClient())
{
// create URL string and fill it in with data (app Id, secret, and current token)
var extendTokenUrl = string.Format(
"https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=fb_exchange_token&fb_exchange_token={2}",
FB_APP_ID,
FB_APP_SECRET,
currentToken);
// send GET request and download the response
var response = req.DownloadString(extendTokenUrl);
// if all is good, response will be a string which looks like this:
// access_token=<<THE TOKEN GOES HERE>>
var newToken = response.Substring("access_token=".Length);
// now save newToken in your DB INSTEAD of currentToken -
// so all calls will be made with extended token
SaveTokenInDB(newToken);
}
hope that helps, and translating this into Java should be straightforward.

Categories

Resources