Android Volley Cache on LastModified - java

The server returns a "Last Modified" header based on when the data changes. Need to use this to cache the response in volley.
My Volley request looks something like this:
StringRequest req = new StringRequest(Request.Method.GET, requestUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray result = new JSONArray(response);
callback.onSuccess(result);
} catch (JSONException je) {
callback.onSuccess(new JSONArray());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
}
});
Can find examples to cache based on a fixed time - say cache for 5 mins:
Android Setup Volley to use from Cache
But this doesnt solve my purpose. The server response has to be invalidated based on the "Last Modified" header. So I'm expecting volley to make the request and get a 304 Not Modified response and hence serve the content from the cache.
Even tried a custom header parser something like this:
https://github.com/mcxiaoke/android-volley/blob/master/src/main/java/com/android/volley/toolbox/HttpHeaderParser.java
But this doesnt seem to do the trick either.

Related

android volley - can't read data from local host

I wrote android app to read json using volley.
If i use example URL from internet - i don't have problem, the data is read. But when i try to read data from local host, I am getting an error.
The same data i can see in web browser in my emulator.
my URL: "http://10.0.2.2/volley_sample/get_data.php"
my code:
private void sendGetRequest() {
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
String url = "http://10.0.2.2/volley_sample/get_data.php"; //it doesn't work
//String url ="https://reqres.in/api/users/2"; //it works
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 10 characters of the response string.
get_response_text.setText("Response is: " + response.substring(0, 10));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
get_response_text.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
adres "http://10.0.2.2/volley_sample/get_data.php" works in web browser in my emulator.
I tried also "http://192.168....", "127.0.0.1....", "localhost/volley_sample...." etc., and neither works.
adres "https://reqres.in/api/users/2" (example from internet) work without problem.
ofc. i added "<uses-permission android:name="android.permission.INTERNET"/>"
I have no idea what I am doing wrong :(

How can I make my code a synchronous POST volley request?

I'm building a tracking app for exercise. As the gps updates every 1 second, the latitude and longitude is added to an array. At the end of the exercise, when you press save, below method is executed, sending all co-ordinates to a database. Because it's an asynchronous request, the co-ordinates don't get loaded into the database in correct order. How can I fix this so it will wait until each iteration of loop is complete or something like that. Thanks
/* Inserts the latitude and longitude points from the latitudeAndLongitudePoints ArrayList
into the latitudeandlongitudepoints table in db*/
private void insertLatitudeAndLongitudePoints(){
//iterates though array of co-ordinates, and adds to database
for(int loop=0; loop<latitudeAndLongitudePoints.size();loop++) {
final int index = loop;
StringRequest stringRequest = new StringRequest(Request.Method.POST,
"http://rrush01.lampt.eeecs.qub.ac.uk/insertLatitudeAndLongitudePoints.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Latitude", String.valueOf(latitudeAndLongitudePoints.get(index).latitude));
params.put("Longitude", String.valueOf(latitudeAndLongitudePoints.get(index).longitude));
params.put("User", AccountInfo.accountEmail);
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(stringRequest);
}
}
Add dependency for Volley library in your build.gradle.
compile 'com.android.volley:volley:1.0.0'
Volley is a network library which makes fast and easier to make HTTP Request for android application. Using Volley library we don’t need to create AsyncTask to make multiple API calls in volley there is RequestQueue where we can enqueue each request. Here in this example, We used Google place autocomplete API. We are going to make synchronous HTTP Request using volley. To make synchronous HTTP request make a RequestFuture object. And make JsonObjectRequest pass this parameter RequestMethod, URL, pass object of type Json and pass RequestFuture instance.
RequestFuture<JSONObject> requestFuture=RequestFuture.newFuture();
final String mURL = "https://maps.googleapis.com/maps/api/place/
autocomplete/json?key="+KEY+"&input=" + input;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,
mURL,new JSONObject(),requestFuture,requestFuture);
MySingleton.getInstance(mContext).addToRequestQueue(request);
Add your request in RequestQueue. Now, whenever the user makes an HTTP request each request added to RequestQueue.To get response object from the requestFuture we call get() method. And we also set a timeout of let’s say 10 seconds so we don’t block the UI thread indefinitely in case our request times out.
try {
JSONObject object= requestFuture.get(10,TimeUnit.SECONDS);
} catch (InterruptedException e|ExecutionException e|TimeoutException e) {
e.printStackTrace();
}
Hope this helps you to understand how we can use volley used to make the synchronous HTTP request

Can not store response data public to access outside in android

I can get very strange issue in my project. I can get the response from volley over the internet and after reposne I want to store it in sharedpref, but issue is that when I get the response and showed up within resonse function then it shows correct data, but when I used to save it outside the response function sharedpref it gives 0. I declared the string public and top of the class but got no luck. Am very strange whats the issue.
SharedPreferences savelogin = getSharedPreferences("login",MODE_PRIVATE);
final SharedPreferences.Editor slogin = savelogin.edit();
String url = "https://datafinderdatabase.xyz/dfapi/FetchId.php?username="+fuser;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
userid = response.toString();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toasty.error(getApplicationContext(), "Network Issue", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
slogin.putString("username",fuser);
slogin.putString("password",fpass);
slogin.putString("userid",userid);
slogin.commit();
This is because your call to the API is asynchronous. Therefore, the result you get back may be processed after that function finishes. To solve this, you can take a Interface approach, explained here for a similar issue:
wait until firebase retrieves data
OR: you need to save the variable to the shared preferences inside the onResponse function.
These:
slogin.putString("username",fuser);
slogin.putString("password",fpass);
slogin.putString("userid",userid);
slogin.commit();
must be inside this:
#Override
public void onResponse(String response) {
userid = response.toString();
//here
}

How to handle 403 error to calling SharePoint list from android?

I want to call SharePoint rest API form android. for this, i'm using cookies to call rest API using web view, but while calling am getting "BasicNetwork.performRequest: Unexpected response code 403".
if l call to SharePoint rest api using volley here what i tried up to.
update:i'm using this site for refrence SharePoint rest api from android
**Update:during research i found one example to connect with share point online using soap as well, any idea how to do that? **
private void sendAndRequestResponse() {
//RequestQueue initialized
Log.d(TAG, "Starting volley request to graph");
/* Make sure we have a token to send to graph */
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject parameters = new JSONObject();
try {
parameters.put("key", "value");
} catch (Exception e) {
Log.d(TAG, "Failed to put parameters: " + e.toString());
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url,
parameters,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
/* Successfully called graph, process data and send to UI */
Log.d(TAG, "Response: " + response.toString());
Toast.makeText(MainActivity.this, ""+response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Cookie","rtFa=" + RTFA + "; FedAuth=" + FedAuth);
headers.put("Accept","application/json;odata=verbose");
headers.put("Content-type","application/json;odata=verbose");
return headers;
}
};
Log.d(TAG, "Adding HTTP GET to Queue, Request: " + request.toString());
request.setRetryPolicy(new DefaultRetryPolicy(
3000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
}
I used rtfa and fed cookies to pass as header.
Update: i used share point login URL for windows auth. for and after success i store rfta and fed auth. cookies to pass token as header but i'm getting same error.

WearOS cannot make Volley request to an endpoint running on my computer's localhost

Problem
I'm attempting to make a simple POST JsonObjectRequest from a Huawei Watch and I keep getting com.android.volley.TimeoutError. I can successfully make other POST JsonObjectRequests from the watch to a different endpoint (not on my computer's localhost) and I can successfully make requests to the desired endpoint from a laptop.
What I've Tried:
Most posts suggest that this error is due to a bad connection or an incorrect endpoint. I tried increasing the timeout period to see if my connection was just slow but this did not fix things. The endpoint is definitely correct as it works when I make the request from a laptop.
I read on several posts that there are issues when connecting to unknown certificates. I followed the quick fix outline here: https://newfivefour.com/android-trust-all-ssl-certificates.html but this made no difference
My Code
mRequestQueue.add(volleyRequest());
...
private JsonObjectRequest volleyRequest(){
JSONObject data = null;
try{
data = new JSONObject("{'some':'data','other':'data'}");
} catch (JSONException e){
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(POST, mPath, data,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("Volley Response", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley Error", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", mToken);
return headers;
}
};
return request;
}

Categories

Resources