Getting error when trying to upload data to server - android

I have been trying to upload my data from android to my server using java, volley and laravel but I am getting. BasicNetwork.performRequest: Unexpected response code 500. I have used postman to test my api and it is working perfectly well.
What could be the cause?
Java code
RequestQueue queue = Volley.newRequestQueue(this); // this = context
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
pd.dismiss();
Log.i("error", String.valueOf( response.toString()));
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Toast.makeText(SignUpActivity.this, "Network Error. Please Try Again.", Toast.LENGTH_LONG).show();;
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("email", email);
parameters.put("password", password);
parameters.put("vCode", vCode);
parameters.put("phone",phone);
return parameters;
}
};
queue.add(postRequest);

Code 500 means that there's a problem at server side. If you're using laravel you should have a web server (as apache, nginx...) which generates error logs.
Check error logs and there you may find what the error is (maybe your app is sending data in a way that server doesn't understand, data is not being sent properly...).
Apache error log location in Linux
Nginx error log location

Related

Volley 405 error : com.android.volley.ClientError

this is my code and it works well for all api except one and throws 405 error
public void postDataVolley(final String requestType, String url, final HashMap params){
try{
StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (mResultCallBack!=null){
mResultCallBack.notifySuccess(requestType,response);
}
Log.i("Volley Response",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallBack!=null){
mResultCallBack.notifyError(requestType,error);
}
Log.i("Error Response", String.valueOf(error));
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> paramsPass=params;
return paramsPass;
}
};
MySingleton.getInstance(mContext).addToRequestQueue(stringRequest);
}catch (Exception e){
}
}
i called the above method using this code from other class as given below
volleyService=new VolleyService(this,mContext);
volleyService.postDataVolley("POST", url, params);
when i search for 405 error everyone suggest me to change the method POST to GET but the api requires POST method..
What is 405 error..?
How can i resolve it
The 405 Method Not Allowed is an HTTP response status code indicating that the specified request HTTP method was received and recognized by the server, but the server has rejected that particular method for the requested resource. This message is distinctly different from the 404 Not Found code.
404 Not Found error indicates that the requested resource could not be found, and is often the result of an incorrect URL, or trying to access a resource for which the client has inadequate permissions. Conversely, a 405 code response confirms that the requested resource is valid and exists, but the client has used an unacceptable HTTP method during the request.
For More Click Here

Volley not attaching parameters to my url via POST request with StringRequest

I am trying to use volley to add a score to my database. I have tested my URL with a POST request using Postman, I have also manually typed the URL with parameters in the android app to the POST request, and that works. so I assume that my issue is in my android code? Or do I have to use the getParams to manually build the url string?
the error I'm getting from my backend:
Error: ER_BAD_FIELD_ERROR: Unknown column 'undefined' in 'field list'
which makes me think that my parameters aren't getting initialized prior to the StringRequest being called.
public void submitHighScore(){
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Toast.makeText(context, response , Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Toast.makeText(context, "Error: unable to submit Score " + error , Toast.LENGTH_SHORT).show();
}
}
){#Override
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError
{
Map<String, String> params = new HashMap<String, String>();
params.put("playerName", "Android test");
params.put("playerScore", "3000");
return params;
}
};
HighScoreSingleton.getInstance(context).addToRequestQueue(postRequest);
For those who may or may not believe me about my code on my server side.
app.post('/api/highScore', function(req,res){
var con = mysql.createConnection({
host: "xxxx",
user: "xxxx",
password: "xxxx",
database: "xxxx"
});
if(req.query!=null){ //
console.log(typeof req.query.playerName);
con.query(`INSERT INTO xxxx (playerScore, playerName) VALUES
(${req.query.playerScore}, "${req.query.playerName}" )`, // async, runs callback aka function
function(err,rows){
if(err) throw err;
res.setHeader('Content-Type', 'text/plain');
res.send('Updated High Score');
});
con.end();
}
});
Thank you in advance, It's very possible I'm overlooking something very simple, otherwise I will just modify my URL in my StringRequest as this seems a bit silly, given the getParams method.
I Hope this will work for you.
I think you need to add header
Override this method.
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = super.getHeaders();
if(params==null)params = new HashMap<>();
params.put("Content-Type","text/plain");
return params;
}

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...

consume Asp.net MVC api from android volley

i am trying to consume a MVC 4 api from my android application
i am using Volley library and it work fine to get data from server
the problem is when i try to send data to the web service which i understand it should be done by using post Method and JsonObjectRequest
my method in MVC Api is :
public class ItemController : ApiController
{
public IEnumerable<string> Post(List<string> val)
{
return val;
}
}
and for volley :
String tag_string_req = "req_login";
Map<String, String> params = new HashMap<>();
params.put("email", "S#b.Com");
params.put("username", "basheq");
JsonObjectRequest req = new JsonObjectRequest(Method.POST ,
AppConfig.URL_REGISTER, new JSONObject(params),new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.d(TAG, "Login Response: " + jsonObject.toString());
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req, tag_string_req);
but i keep getting null in response and it look like the api doesn't parse the parameter .
what is wrong ?? , and is this the proper way to do it or is there a better way ??
The main problem was that i was setting list as a parameter which for some reason does not work
the solution was by wrapping the input parameter into a class and of course change the json structure to correspond to that

Sending login params to Rails server using Volley

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

Categories

Resources