I'm searching now for a few days to figure out why my POST request takes so long to load. I'm using the volley library instead of a HTTPRequest.
This is how I'm doing the request:
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
...
JSONObject jsonObject = new JSONObject();
jsonObject.put("geoLong", longitude);
jsonObject.put("geoLat", latitude);
jsonObject.put("radius", 5);
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, URL,
jsonObject, createResponseListener(), createErrorListener());
jsonRequest.setShouldCache(false);
jsonRequest.setRetryPolicy(new DefaultRetryPolicy(15000, 2, 1));
jsonRequest.setTag(requestTag);
requestQueue.add(jsonRequest);
The request takes about 10-15 seconds to load until I receive the response which is just ridiculous because the response size is about 1886 bytes. I tested it with a good WLAN connection and also with 3G.
If I'm doing the request with Postman on my Laptop over WLAN it only takes around 400ms so it's not a server-side problem. I'm confused why does it take so long to make this volley request, am I doing something wrong?
Normally volley not taken more time.
you can check by your self.
private long mRequestStartTime;
public void performRequest()
{
mRequestStartTime = System.currentTimeMillis(); // set the request start time just before you send the request.
JsonObjectRequest request = new JsonObjectRequest(URL, PARAMS,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
// calculate the duration in milliseconds
long totalRequestTime = System.currentTimeMillis() - mRequestStartTime;
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
long totalRequestTime = System.currentTimeMillis() - mRequestStartTime;
}
});
requestQueue.add(request);
}
If still you will face issue then you can go with Retrofit:http://square.github.io/retrofit/
Related
I am learning about Volley and I don't know why the response from GET method is coming as a single char -> [.
I am using this method to get the JSON response:
public void getJsonMethod() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(context);
// String url = "https://www.w3schools.com/js/myTutorials.txt";
String url = "http://www.google.com"; // with this url I am getting response
// Request a string response from the provided URL.
final StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("Response is: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Response is not good" + error.getMessage());
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
When I am using this link I do get a response but when I try to use some link that contains nothing but JSON like this one my response it "[".
I am calling this method from Activity like this:
GetJsonClass getJson = new GetJsonClass(this);
getJson.getJsonMethod();
Any ideas on what am I doing wrong here?
Answer + code
If anyone will start using Volley maybe this can help him :
as David Lacroix said in his answer, I called stringRequest and notJsonArrayRequest.
Here is how it should have been:
public void getJsonMethod() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(context);
String url = "your url";
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
System.out.println("this is response good" + response);
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("this is response bad" + error);
}
});
queue.add(jsonObjectRequest);
}
See https://developer.android.com/training/volley/request
StringRequest. Specify a URL and receive a raw string in response. See Setting Up a Request Queue for an example.
JsonObjectRequest and JsonArrayRequest (both subclasses of JsonRequest). Specify a URL and get a JSON object or array (respectively) in response.
You should be using a JsonArrayRequest
myTutorials.txt is being served with status code 304 (no proper suffix and MIME type either):
304 Not Modified. If the client has performed a conditional GET request and access is allowed, but the document has not been modified, the server SHOULD respond with this status code. The 304 response MUST NOT contain a message-body, and thus is always terminated by the first empty line after the header fields.
In other terms, what the browser may display is not neccessarily the same what the server has sent. eg. GSON would accept that JSON only with option lenient enabled, because the array has no name.
see RFC 2616.
I'm using Volley to send Get method.Sometimes I have 502 bad gateway server error.I don't know what is a wrong or how i can solve my problem
This is a source code
public void polygonRequest(final String userID, final String secretKey) {
showpDialog("loading");
polygonModelList.clear();
String url = ServerUtil.polygon+userID+"/"+secretKey;
final JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
SavedPolygonJson polygonModel=new SavedPolygonJson();
polygonModel.setPolygonJson(response.toString());
polygonModel.saveInStorage();
parsePolygonRequest(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hidepDialog();
showOneItemDialog(error.toString(),false);
}
});
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
CoreApplication.getInstance().getRequestQueue().add(jsObjRequest);
}
When I send my request with browser i have not any errors.How i can fixed this error...
How i can combine browser's request header with Volley request header?
thanks
Increase the the read time out session if you are using the retrofit.
Or in case of volley in crease the request time session from its default
for cross check hit the url directly in web browser and calculate the time that how much time it takes to fetch the response according to that you set the request session time
This happens because if your network lib does not get the response on predefined request time it show bad gateway 502
(Sorry for any english mistake its not my native language)
I'm trying to parse html using Volley and Jsoup.
while debugging / running the app, the StringRequest dosent invoke onResponse() or onErrorResponse(), basically there no response or Error from the Response.Listener (i guess).
so i cant "begin" parsing the html because the onResponse() is never invoked.
Ive searched for answer and nothing seems to get it fixed.
Could it be that the RequestQueue cache kicks in and its not trying to get the response? (just brain storming tried so many things).
--Im just trying to retrive data from html, so i could show the updated data from the url in my app, is Volly the way or should i use simpler mathods?
here is my volley StringRequest and RequestQueue:
String url = "http://www.fringeb7.co.il/";
final RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
// 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) {
response_utf8 = URLDecoder.decode(URLEncoder.encode(response, "iso8859-1"),"UTF-8");
doc = Jsoup.parse(response_utf8);
Log.d("logr=",response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.d("log2=", error.toString());
requestQueue.stop();
}
});
// Add the request to the RequestQueue.
requestQueue.add(stringRequest);
took me long enough, but there was no problem.
the code works, while debugging there were no response,
but when i run the app the request complete and i got the wanted response.
so if anyone have a similier problem, from some reason while debugging I dident get response but while running the app its working fine.
(simpley dident know that)
try this first before wasting time in debugging like i did.
If you use Jsoup, you can get it and parse in very simple way:
Document doc = Jsoup.connect("http://www.fringeb7.co.il/").get();
If you still want to use Volley, below code works perfectly in my device:
String url = "http://www.fringeb7.co.il/";
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
// 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) {
try {
String response_utf8 = URLDecoder.decode(URLEncoder.encode(response, "iso8859-1"), "UTF-8");
Document doc = Jsoup.parse(response_utf8);
Log.d("logr=", "title = " + doc.title());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.d("log2=", error.toString());
//requestQueue.stop();
}
});
// Add the request to the RequestQueue.
requestQueue.add(stringRequest);
requestQueue.start();
Output of the above code:
D/logr=: title = תיאטרון הפרינג' באר שבע
try 'https' instead of 'http' in your url
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
I'm using Volley library to access my server data.Volley has inbuilt caching function.I tried to use that as follows.this out put "CACHED RESPONSE". but i don't know how to access the cached data.
void initHttpCall(){
RequestQueue queue = Volley.newRequestQueue(mcontext);
UOBRequest<RateData> myReq = new UOBRequest<RateData>(Method.GET,
Constants.GET_RATES,
RateData.class,
mlistner,
createMyReqErrorListener()){
#Override
public Map<String, String> getHeaders(){
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", getToken());
headers.put("Accept","application/json" );
return headers;
}
};
myReq.setShouldCache(true);
if(queue.getCache().get(Constants.GET_RATES)!=null){
System.out.println("CACHED RESPONSE");
}else{
queue.add(myReq);
}
}
}
This is my response listner and want to get RateData object here.
new Response.Listener<RateData>() {
#Override
public void onResponse(RateData rateData) {
setupCurrencyPager(rateData);
setLastUpdatedTime();
}
});
You misunderstood how Volley's caching system works. The beauty of it is that as a user of Volley, you are unaware of where the response is coming from.
When you add a new request to the RequestQueue, Volley checks if that request already has a cached response. If it does, and that response has not expired yet, it is returned immediately. Otherwise, it goes outside to the network, retrieves the response, caches it and returns it to you.
You don't need that last if statement, simply add it to the queue and Volley will take care of the rest.
try the following code.it will help you sure.
please create a request which you want to pass to server.
JSONObject request = new JSONObject();
request.put("user","user2");
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url, request, new Response.Listener() {
#Override
public void onResponse(JSONObject response) {
// TODO Auto-generated method stub
Log.v("response:-"+response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(jsObjRequest);
}