I just started to use Volley's library to make http calls, and I tried to use the RequestFuture class for synchronous requests, but I fail my attempt to make a simple request. Any idea of what I am doing wrong?
RequestQueue requestQueue = Volley.newRequestQueue(this);
String url = "http://myapi-oh.fr/v2/podcasts/x/shows/" + points.get(0).getShowId() + "/streams";
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(url, null, future, future);
requestQueue.add(request);
try {
JSONObject response = future.get(10, TimeUnit.SECONDS);; // this will block (forever)
points.get(0).setStreamUrl(response.getJSONArray("result").getJSONObject(0).getString("url"));
} catch (InterruptedException e) {
Log.d(TAG, "error : " + e);
// exception handling
Log.d(TAG, "error : " + e);
} catch (ExecutionException e) {
// exception handling
Log.d(TAG, "error : " + e);
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "error : " + e);
} catch (TimeoutException e) {
e.printStackTrace();
}
To make a simple request just use the StringRequest class. Below is a small snippet:
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest req = new StringRequest(Request.Method.POST, "your_url", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//handle response here.
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
//handle error here.
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//return params(if any) to server here.
return super.getParams();
}
};
queue.add(req);
Related
I'm getting a Null Exception with JSon object from Volley
I filled the JSon object before it is used, and not in the parameterlist.
public static void SendPost6(final Context context){
final String TAG= "-->Error-->";
String url = "http://192.168.44.120/test_php_neuer_user.php";
RequestQueue queue = Volley.newRequestQueue(context);
JSONObject userObject = new JSONObject();
JSONObject paramsObject = new JSONObject();
try {
paramsObject.put("name", "Name");
paramsObject.put("email", "EMail");
userObject.put("user",paramsObject);
}
catch (JSONException e){
Toast.makeText(context, "JSON-Error:" + e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url,
userObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(context, "Volley Response:" + response.toString(), Toast.LENGTH_LONG).show();
}},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//handle errors#
Log.d(TAG, "Failed with error msg:\t" + error.getMessage());
Log.d(TAG, "Error StackTrace: \t" + error.getStackTrace());
Toast.makeText(context, "Volley Error:" + error.getMessage(), Toast.LENGTH_LONG).show();
error.printStackTrace();
try {
byte[] htmlBodyBytes = error.networkResponse.data;
Log.e(TAG, new String(htmlBodyBytes), error);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
});
queue.add(request);
//AppController.getInstance().addToRequestQueue(request);
I want to add the json object request into the queue to perform http-post. Volley Error is "null"
The firewall blocked the network access. This is why i'm getting response null. Solved.
I have a Stringrequest in Android Studio and it's working correctly, I mean I get the response on onResponse method, now I want volley to return an error when the error key has true value. how can i do it?
this is my request:
StringRequest stringRequest = new StringRequest(Request.Method.POST, METHOD_ACCOUNT_OTP_REQUEST,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("response", response);
try {
JSONObject jsonObject = new JSONObject(response);
startVerificationActivity(jsonObject.get("sender").toString());
} catch (JSONException e) {
e.printStackTrace();
Log.i("error", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("mobilePhoneNumber", phoneNumber);
params.put("clientId", CLIENT_ID);
return params;
};
this is the answer of the server:
{"sender":"10008727","error":true}
all I want is to set volley to run onErrorResponse when error is true in the json.
You can create a new custom AppStringRequest class which inherits from StringRequest and handle the above usecase.
public class AppStringRequest extends StringRequest {
// ... constructor ...
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
// You will receive your response here in the response parameter.
// parse the response and check whether the response has "error":true
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
// if it's an error, return Response.error(), otherwise, return Response.success()
try {
JSONObject resObj = new JSONObject(parsed);
boolean error = resObj.getBoolean("error");
if (error) {
return Response.error(new VolleyError());
} else {
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
} catch (JSONException e) {
e.printStractTrace()
// your server response has some issues
}
return Response.error(new VolleyError("Error message")); // can send error message in the VolleyError
}
}
Then you have to use this AppStringRequest instead of the default StringRequest.
StringRequest stringRequest = new AppStringRequest(Request.Method.POST, METHOD_ACCOUNT_OTP_REQUEST,
... )
The error message will be available in the onErrorResponse:
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley error", error.toString()); //the error message
}
I am trying to cache data for offline usage without success. Below is my work so far.
//fetch news details
private void FetchHeadline(){
showDialog();
btnRefresh.setVisibility(View.GONE);
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(NEWS_URL);
if (entry != null) {
Log.e("", "babaaaaaaaaaaaaaaaaaaaaaaaa");
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONArray(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonArrayRequest jsonReq = new JsonArrayRequest(
NEWS_URL + dbHelper.getAuth().getString(0), new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
hideDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
btnRefresh.setVisibility(View.VISIBLE);
hideDialog();
Log.e(TAG, "Response: " + error.getMessage());
try {
if (error.getMessage().equalsIgnoreCase("java.io.IOException: No authentication challenges found")){
moveToLoginActivity();}
}catch(Exception e){}
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
I added the following to my .htaccess with no success
<IfModule headers_module>
# 1 Month for most static assets
<filesMatch ".(css|jpg|jpeg|png|gif|js|ico)$">
Header set Cache-Control "max-age=36000, public"
</filesMatch>
</IfModule>
I am trying to send some authentication headers from GET request and I tried using Volley JsonObjectRequest call :
Map<String,String> params=new HashMap<String,String>();
params.put("token","fghjbvjhnjjk");
activity.showDialog();
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,url,
new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(tag, response.toString());
activity.hideDialog();
try {
activity.onRequestServed(response, code);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(tag, "Error: " + error.getMessage());
Log.e(tag, "Site Info Error: " + error.getMessage());
Toast.makeText(activity.getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
activity.hideDialog();
try {
activity.onRequestServed(null,code);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
req.setShouldCache(true);
But its showing:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
at com.android.volley.Request.<init>(Request.java:136)
at com.android.volley.toolbox.JsonRequest.<init>(JsonRequest.java:58)
at com.android.volley.toolbox.JsonObjectRequest.<init>(JsonObjectRequest.java:47)
I read somewhere that you can pass headers by making a hashmap and thus create a new JsonObject with that parameter. Maybe that will work on a POST request. Please help..
Well, the thing is simple and very precise. Passing headers to either GET or POST request, you need to override getHeaders method in JsonObjectRequest Class. This is how it will be done:
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,url,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(tag, response.toString());
activity.hideDialog();
try {
activity.onRequestServed(response, code);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(tag, "Error: " + error.getMessage());
Log.e(tag, "Site Info Error: " + error.getMessage());
Toast.makeText(activity.getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
activity.hideDialog();
try {
activity.onRequestServed(null,code);
} catch (JSONException e) {
e.printStackTrace();
}
}
}) {
/**
* Passing some request headers
*/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
//headers.put("Content-Type", "application/json");
headers.put("key", "Value");
return headers;
}
};
Hi I am a beginner in Android , I am learning to make Api Calls. I got a tutorial of Volley which uses GET to Receive response. Now I want to Send Post request Using Volley. I don't know how to do that, what would be the code for POST in the given Tutorial. Please guide me to send Post Request.The link to the tutorial that I am learning is http://www.truiton.com/2015/02/android-volley-example/
you have to used below code to send request
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
try {
/** json object parameter**/
JSONObject jsonObject = new JSONObject();
jsonObject.put("hello", "hello");
Log.e("jsonObject params", jsonObject.toString() + "");
/**URL */
String url ="http://google.com"
progress.setVisibility(View.VISIBLE);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
progress.setVisibility(View.GONE);
Log.e(TAG, "Response " + jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
progress.setVisibility(View.GONE);
Log.e(TAG, volleyError);
Util.showToast(activity, "Please try again");
}
});
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
progress.setVisibility(View.GONE);
Log.e(TAG, e);
}
catch (Exception e) {
progress.setVisibility(View.GONE);
Log.e(TAG, e);
}
}
}
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(jsonObjectRequest);
You can follow this :http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
StringRequest request = new StringRequest(Method.POST,
"post url",
new ResponseListener() {
#Override
public void onResponse(String response) {
Log.d("response", response);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("response","error");
}
}) {
// post params
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("param", "param");
return params;
}
};
//2.Use your custom volley manager send request or like this
Volley.newRequestQueue(mCtx).add(request);