Volley throw 502 bad gateway - android

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

Related

Why Volley response is received as "[" and not JSON

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.

Unexpected response code 307 for GET request for local service

I'm trying to connect to a localhost web service that I wrote in .net core 2.0. Using the emulator's browser I was able to invoke it and get JSON data back. However, inside my app when I try to get it I'm getting response code 307 back.
public void onClick(View view)
{
String url = String.format("http://10.0.2.2:5000/api/testservice/tickerpnl?ticker=%s&purchaseDate=%s&shares=%s/"
, tickerText.getText().toString(), dateText.getText().toString(), sharesText.getText().toString());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try
{
double pnl = response.getDouble("PNL");
} catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(jsonObjectRequest);
}
On the stacktrace I'm getting the following:
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
E/Volley: [403] BasicNetwork.performRequest: Unexpected response code 307 for http://10.0.2.2:5000/api/testservice/tickerpnl?ticker=AAPL&purchaseDate=1-1-15&shares=1
Again using the link from the stack trace I was able to get the JSON data back just pasting it into the emulator's browser but somehow it just won't work using JsonObjectRequest.
the requestqueue was initialize as
private RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
I found out the issue was that for .net core I had code that redirect http to https so that's why I was getting the 307 error since I was trying to call it using http

Android volley JsonObjectRequest takes too long

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/

BasicNetwork.performRequest: Unexpected response code 429 (android)

I m using Volley library for sending a request to server for Login to an app. it doesn't have any problem until couple of hours ago. but without any reason, i m getting this error "BasicNetwork.performRequest: Unexpected response code 429"
the code is this:
public void loginRequest(final String username, final String password) {
String URL = Misc.Server_Url() + "login";
final StringRequest sr = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject obj;
try {
obj = new JSONObject(response);
if (obj.getInt("success") == 1) {
startActivity(new Intent(ActivityLogin.this, ActivityArticles.class));
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("username", username.trim());
params.put("password", password);
return params;
}
};
RetryPolicy policy = new DefaultRetryPolicy(2 * 1000, 2, 2);
sr.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(sr);
}
I have searched in Wikipedia for this error (429) and i find that it means : "The user has sent too many requests in a given amount of time"
from server side(php) for more security if from an ip get more than for example 60 request within 10 second it will block that ip for a while... and client get 429 error code. i m wondering how it will occure when i send a single request to server same as above code!!! and in policy i set the try to 2 times Not more than that. i dont know why when i send this request i get error 429. means you have send 60 request within limited period of time.
do you know how to solve this problem?
thanks in advance...
Yes, as you said, the 429 response code states so. However, the tricky part is that the server sends this response code for either
You have sent too many requests in a short duration
The server has received too many requests by many others during that time
If you read the RFC related to the response code, you'll see that the RFC does not state that the server must identify individual users and only send them the busy status: 429. It could be because others are sending too many requests and the server is sending a 429 response to all.
In addition, the RFC states that the server should respond with a 429 response and the server MAY send the following parameter in its response header.
Retry-After: 3600
This would mean you should retry after this timeout.
the reason was coz of caching system in server.
if we send new request each time, it works fine. but if our request use from caching strategy system in server... it occur 429 error number...

Android Volley JsonObjectRequest returns same response every time on mobile data

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

Categories

Resources