This is basically my end url which is giving me correct address component in the browser. But when I am using volley to fetch the same data I am getting error 403.
final StringBuilder url = new StringBuilder(
"http://maps.googleapis.com/maps/api/geocode/json?sensor=true&latlng=");
url.append(latitude);
url.append(',');
url.append(longitude);
url.append("&language=");
url.append(Locale.getDefault().getLanguage());
// Request a string response from the provided URL.
#SuppressWarnings("rawtypes")
StringRequest stringRequest = new StringRequest(Request.Method.GET, url.toString(),
new Response.Listener() {
#Override
public void onResponse(Object arg0) {
// TODO Auto-generated method stub
System.out.println();
try {
String address = (new JSONObject(arg0.toString())).getJSONArray("results").getJSONObject(0).getString("formatted_address");
location.setText(address);
ProjectUtil.crossfade(layout, progress);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println();
}
});
queue.add(stringRequest);
With the API request in the REST client gives the response that is expected out of it. In these cases it is always the network that cause trouble, Please check to see the network you are using for your android app to make connection is a shared network? And/or one that uses a proxy for outgoing
requests? Looks like someone on the same network is
downloading stuff from Google and causing blocks.
One reason may be also because you are exceeding the API request limit. For more details read about the quota request.
For more information, I would like to see the logcat!!
Related
Here is my function which I filled in from https://developer.android.com/training/volley/request#java
String url = "http://192.168.1.31:8000/api/social/convert-token";
JSONObject jsonBody = new JSONObject();
try{
jsonBody.put("grant_type", "convert_token");
jsonBody.put("client_id", clientID);
jsonBody.put("client_secret",clientSecret);
jsonBody.put("backend", "facebook");
jsonBody.put("token", facebookAccessToken);
jsonBody.put("user_type", userType);
}catch (JSONException e){
e.printStackTrace();;
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, url, jsonBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Execute Code
Log.d("LOGIN TO SERVER", response.toString());
// Save server token to local DB
SharedPreferences.Editor editor = sharedPreferences.edit();
try {
editor.putString("token", response.getString("access_token"));
}catch (JSONException e){
e.printStackTrace();
}
editor.commit();
//Start home activity
startActivity(new Intent(Login.this,Home.class));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
The string URL is my Django server, this works properly, I can access it from the web browser on the android phone.
The next block of just converts data I previously got into JSON format. I tested this by copying and pasting the URL, and each parameter in Postman, and it works and returns JSON back.
jsonBody is then passed into the Json Request, along with the URL. The Log.d "LOGIN TO SERVER", is not visible in my log. So I know that the onResponse does not run. Further I put a Log line in the onErrorResponse, and it was visible in my log.
So onReponse does not run, while onError response does. I don't know what the error is.
Three cases,
Check if there are any headers to pass using getHeaders().
2.As it is http and not https, provide android:usesCleartextTraffic="true" in manifest inside . It allows you to access http urls also.
3.You said you have kept logger in Response.onErrorListener(){} and what is the error. If not give it by Log.d("Error", "Error getting "+error.toString);
I have the following code which works to make a call and receives xml.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
Log.e(TAG, "response from RRSendCarerLocation = " + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
Log.e(TAG, "error: RRSendCarerLocation = " + error);
}
});
rq.add(stringRequest);
.
The problem i have is, this works fine when called from an Activity but i want to use Volley from an IntentService. An intentService destroys itself after the work is done, so the Volley callbacks never retreive the response.
one solution i have found would be to use RequestFuture and call .get() to block the thread. i have an example below that i found here.
Can I do a synchronous request with volley?
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(URL, new JSONObject(), future, future);
requestQueue.add(request);
try {
return future.get(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// exception handling
} catch (ExecutionException e) {
// exception handling
} catch (TimeoutException e) {
// exception handling
}
.
I don't want to use JSON as the server returns xml. i've looked at the StringRequest class but i cannot see anything that supports a RequestFuture.
http://griosf.github.io/android-volley/com/android/volley/toolbox/StringRequest.html
Is there anyway to use the StringRequest code to return xml using the blocking functionality of RequestFuture
thanks
This is in case you did not find an optimum solution or for any people who come across this post with the same question. If you want to use StringRequest with FutureRequest you can try out the solution below.
// Setup a RequestFuture object with expected return/request type
RequestFuture<String> future = RequestFuture.newFuture();
// organize your string request object
StringRequest request = new StringRequest(url, future, future);
// add request to queue
VolleySingleton.getInstance(context).addToRequestQueue(request);
try {
// Set an interval for the request to timeout. This will block the
// worker thread and force it to wait for a response for 60 seconds
// before timing out and raising an exception
String response = future.get(60, TimeUnit.SECONDS);
// Do something with the response
Log.e(TAG, "response from RRSendCarerLocation = " + response);
return Result.success();
} catch (InterruptedException | TimeoutException | ExecutionException e) {
e.printStackTrace();
return Result.retry();
}
I use Retrofit for this types of requests. It is very easy to use and allows you to make both types of requests (sync and unsync)
http://square.github.io/retrofit/
I've searched a lot about this but can't find any solution. I have been using Volley for a long time to handle my network communication. Recently I decided to use a SyncAdapter to sync my data to the server. Inside the onPerformSync() method, I thought I'll use Volley to send the data to the server as its very easy with Volley to make GET, POST requests.
Problem - SyncAdapter and Volley both use their own seperate threads. So when I initiate a Volley request from inside the onPerformSync() method, the SyncAdapter does not wait for the Volley request to complete and finishes the sync before the onResponse() or onErrorResponse() callback of Volley is received. I need to make further network calls inside the SyncAdapter after first call returns successfully.
Example Code -
#Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
JsonObjectRequest jReq = new JsonObjectRequest(Method.POST, url, data,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "response = " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "error = " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(jReq);
//onPerformSync() exits before request finished
}
Question - So how do I make the SyncAdapter to wait until the network response is received by Volley?
Make a synchronous volley request.
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(URL, null, future, future);
requestQueue.add(request);
and then use:
try {
JSONObject response = future.get(); // this will block (forever)
} catch (InterruptedException e) {
// exception handling
} catch (ExecutionException e) {
// exception handling
}
Code from: Can I do a synchronous request with volley?
I am using Volley JsonObjectRequest to get data from server.
code snippet:
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("Response: " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
But I am getting same JSONObject response every time on mobile data connection.
Note: It's work perfectly on WiFi connection.
Is anyone facing this issue ? any solution ?
#BNK request.setShouldCache(false); worked for me. It's issue of volley cache management.
I assume that, when a request is sent:
It would hit the cache first and send that to onResponse
then when the results come through from the remote server it would provide it to the onResponse
If you use any of the default Request classes implemented in volley(e.g. StringRequest, JsonRequest, etc.), then call setShouldCache(false) right before adding the request object to the volley RequestQueue
request.setShouldCache(false);
myQueue.add(request);
You can also set expiration policy for cache.
See this answer for more details
Link to Rails server. https://afternoon-sea-5654.herokuapp.com.
I want to send a simple JSON POST to attempt to login. I get the following volley errors
Error
04-09 14:03:56.156 3002-3031/com.digitalnatives.volleytest E/Volley﹕ [244] BasicNetwork.performRequest: Unexpected response code 500 for https://afternoon-sea-5654.herokuapp.com/sessions/create
04-09 14:03:56.160 3002-3002/com.digitalnatives.volleytest E/Volley﹕ [1] 4.onErrorResponse: Error:
I can't tell if it's down to the way I am formatting the request. Here is an example login request using curl manually.
Login -
curl -X POST -d "user[email]=ywaghmare5203#gmail.com&user[password]=12345678&" https://afternoon-sea-5654.herokuapp.com/sessions/create.json
Request perameter: email, password,
Response Perameter:
{"id":10,"username":"yogeshwaghmare1","email":"ywaghmare5203#gmail.com","password_hash":"$2a$10$pvLhzJlVz8Hl86O7N/ekiO2wrwNxbfTZlYPtccY4f7vXYNFs1vq6a","password_salt":"$2a$10$pvLhzJlVz8Hl86O7N/ekiO","last_login_time":null,"is_active":null,"contact_number":"123456","created_at":"2015-04-01T19:20:37.552Z","updated_at":"2015-04-01T19:20:37.552Z"}
JSONObjectRequest code
public void loginTest() {
private final String LOGIN = "https://afternoon-sea-5654.herokuapp.com/sessions/create";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
// old test code : params.put("user[email]=test1#gmail.com&", "user[password]=12345678&");
params.put("user[email]", "test1#gmail.com");
params.put("user[password]", "12345678");
JsonObjectRequest req = new JsonObjectRequest(LOGIN, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
responseText.setText("Worked!");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
responseText.setText("Nope");
}
});
// add the request object to the queue to be executed
AppController.getInstance().addToRequestQueue(req);
}
Actually in response you are not Getting the JSON data. It is returning a HTML message regarding redirection. Your response is 302
Response code 500 means its a server sided syntax error. You can test your api through online API testing platform like Runscope. It really save our time and confusion when we collaborate with web team and android team.
Runscope Link