Volley 405 error : com.android.volley.ClientError - android

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

Related

Getting error when trying to upload data to server

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

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.

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;
}

Post request to server not properly working Volley

Hi guys i am facing a problem and the problem is that i am trying to send post request to server and i am getting exception
com.android.volley.ParseError: org.json.JSONException: End of input at character 0 of
when i try to send data through get request it is working properly and when i try to send data through post request i am getting the above exception i have tried searching but not succeeded.
below is my code
JsonObjectRequest _send_cab_data_to_server = new JsonObjectRequest(Request.Method.POST,
cab_Data_Url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("", "response : " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("", "error : " + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Method", "CarLocation");
params.put("data", _Cab_Locations_In_Driver_Service);
return params;
}
};
// Adding request to request queue
Volley_Controller.getInstance().addToRequestQueue(_send_cab_data_to_server,
"volley");
}
and the data attribute corresponds to a set of strings that are combined
e.g Ï2|33.7129221|73.0634634|Apr28,201510:50:33AM|0ÎÏ2|33.7129272|73.0634653|Apr28,201510:50:58AM|0Î
and the json response is
{
"Success": true,
"Info": "Successful",
"Response": [
{
"Status": "Done"
}
]
}
when i try to send data through get request it is working properly and
when i try to send data through post request i am getting the above
exception
As you said you are getting below exception:
com.android.volley.ParseError: org.json.JSONException: End of input at character 0 of
This means that you are getting null response. You are supposed to use GET method only, not the POST method because your server is not responding to the post request but rather returning a null object and so your parser is getting failed at parsing null object.
FYI, There is a meaning and importance of GET and POST method. Use the appropriate method defined by your server API.

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