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;
}
Related
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
JSON response from a remote server
{"status":"success",
"data":{"auth_token":"9389e656c90e11c451443657c8e",
"user":{"active_location":" Airport"}}}
I need to store the auth_token and pass to the remote server as the header,
tried addHeader("key1", "value1");
but still not working, need help
To send headers for belly request, you need to override getHeaders() method. Inside method create a map and put your key-value pairs and return the the map.
JsonObjectRequest request = new JsonObjectRequest(requestMethod, yourUrl, postData(if any), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//TODO parse your response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//TODO handle error
}
}){
//Here is the place where you can add your headers
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("key1", "value1");
return params;
}
};
Also if you need to pass any request parameters you can do that in the same way by overriding getParams() method.
For more details check the volley tutorial
You can simply use Base64 to encode the token string and put it in SharedPrefs, then read and decode to send in a header.
I'm trying to communicate between Android and a Flask server I've set up on AWS. I have some data I've put inside a JSONObject, and I'm sending that over a POST request to the server.
The Flask server receives this JSON, parses it, and even does the appropriate manipulations. However, when I send a Response back to Android, it doesn't seem to identify it at all.
I believe I'm going wrong in the Flask return part, but I don't know where exactly.
Here's the Flask return code:
parsed_results = parse_text(results)
#json_x = json.dumps({'id':str(status.inserted_id), 'Result':'OK', 'data': parsed_results})
return Response(json.dumps({'id': str(status.inserted_id), 'Result': 'OK', 'data': parsed_results, 'raw_data': results}), mimetype='application/json'), 200
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
Here's the Android Listener code:
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.POST,
URL,
data,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("JSON_TAG", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
)
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return super.getParams();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
//return super.getHeaders();
Map<String,String> headers = new HashMap<>();
headers.put("Content-Type","application/json");
return headers;
}
};
The Android application just stays idle. Where am I going wrong? Any help would be greatly appreciated. Thanks!
I solved the issue, guys. The problem was very apparent - a mismatched return statement from the server. By using jsonify, I was able to return the data to the server.
from flask import jsonify
results = parse_results(data)
return jsonify(results)
Worked like a charm!
Every time I try to use POST method with Volley, I get sever error. I get null value in getCause, and some default value in getNetworkResponse.toString().
If I use GET method, this works fine (I get response from my url).
Can anybody help what can I do?
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("teststr", "abd");
RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue();
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.POST,
url,
new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Toast.makeText(getApplicationContext(), "Success"+response.toString(), Toast.LENGTH_LONG).show();
}catch(Exception e){
Toast.makeText(getApplicationContext(), "JSON ERROR", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("abd", "Error: " + error
+ ">>" + error.networkResponse.statusCode
+ ">>" + error.networkResponse.data
+ ">>" + error.getCause()
+ ">>" + error.getMessage());
}
}) {
#Override
protected Map<String,String> getParams() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("key", "value");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
requestQueue.add(request);
Error Log:
Error:
Error: com.android.volley.ServerError>>404>>[B#42b1e0d0>>null>>null
UPDATE:
networkResponse.statusCode comes as 404, though the url is accessible (and return data if I just use GET method). If I remove header part in POST method, still the same.
the url:
<?php
$response = array();
$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);
if(!isset($jsonObj['teststr'])){
$response["msg"] = "No data.";
}else{
$response["msg"] = "Success: ".$jsonObj['teststr'];
}
echo json_encode($response);
?>
problem is your Queue.
change your volley code to this:
RequestQueue queue = Volley.newRequestQueue(this);
String URL = EndPoints.BASE_URL + "/call";
StringRequest request = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
Log.d("onResponse", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse response = error.networkResponse;
String errorMsg = "";
if(response != null && response.data != null){
String errorString = new String(response.data);
Log.i("log error", errorString);
}
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("key_1","value_1");
params.put("key_2", "value_2");
Log.i("sending ", params.toString());
return params;
}
};
// Add the realibility on the connection.
request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
// Start the request immediately
queue.add(request);
and your php (laravel) code to this:
$response['success'] = true;
$response['user']['tell'] = $user->tell;
$response['user']['code'] = $user->code;
$response['user']['time'] = $time;
$response['user']['register_state'] = '1'
return response()->json($response, 200);
First, try to make sure your server works well.
You can use Postman(chrome plug-in) or any other way to send a post request to the url and see what it responses.
After make sure there's no problem with your server, let us solve the problem with volley.
There's some problem with JsonObjectRequest when you use POST method.
like this Volley JsonObjectRequest Post request not working.
I suggest you use StringRequest first and overwrite the getParams method like you did before. After you survive this task, you can try to write your own request, not very difficult but very useful.
I also suggest add request.setShouldCache(false) before requestQueue.add(request);. By default, volley saves the response in its cache and this behavior may cause some strange problem.
Well,I think you can first print the responseCode in your logcat
Add this code before add to queue
request.setRetryPolicy(new DefaultRetryPolicy(0, -1,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
sometimes, request is timeout before your php executed completely. so try this code. maybe can help
maybe it's related to your operator...
I have the same issue sending JasonObject with Volley.
I tested my app on 9-10 devices with two different operators.
The request on one operator returns an Error with everything null or blank data in it, on the other one everything works fine and I get my Response from API successfully.
I have no idea what do operators do that causes this problem...
Maybe they use some kind of firewall that blocks sending JsonObject.
I tried to display the response as a String and the error went off.
Use response.toString() wherever you want to display the error or use it.
In my case, the answer is retry policy setting.
I put 30 seconds the timeout value, it should be 30000, not 30.
try to increase timeout. i had the same issue and the request timeout was the problem.
How do I send a DELETE Request using Volley (Android) to a REST Api with parameters like access_token and username. I have tried almost everything on Internet but still I am getting a 400 error Message.
I have tried sending the same DELETE request using PostMan and it works perfectly fine.
Here is the Error:
E/Volley﹕ [1112] BasicNetwork.performRequest: Unexpected response code 400 for http://myserverip/messages/2
and Here is the Java code that I am using:
String URI = "http://myserverip/messages/2";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.DELETE,URI,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(contextm,response.toString(),Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
headers.put("access_token", "access_token");
headers.put("username", "username");
return headers;
}
};
MyApp.getInstance().addToRequestQueue(request);
Might not be really useful but here is the working DELETE request preview from PostMan
DELETE /messages/1 HTTP/1.1
Host: serveripaddress
Cache-Control:no-cache
Content-Type: application/x-www-form-urlencoded
access_token=SPAVYaJ7ea7LzdeQYrBTsIRssuGbVpJI8G9XSV0n&username=whit3hawks
You can easily achieve this if you put the following instead of null in ... new JsonObjectRequest(Request.Method.DELETE,URI,null,new Response.Listener<JSONObject>() { ...
final JSONObject object = new JSONObject();
try {
object.put("access_token", "SPAVYaJ7ea7LzdeQYrBTsIRssuGbVpJI8G9XSV0n");
object.put("username", "whit3hawks");
} catch (Exception e) {
e.printStackTrace();
}
So your Request should look like this:
... new JsonObjectRequest(Request.Method.DELETE,URI,object,new Response.Listener<JSONObject>() { ...
You posted a long time ago, but maybe someone else will need this some time.
I am successfully sending headers in volley while using DELETE with this code:
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
just tried it and works like a charm.
EDIT:
if you're using a Mac, try checking with Charles what exactly it is you are sending,
on a PC you can try fiddler.
also, error 400 means 'Bad Input', so the server is either getting more info then it should, or less then he expects.
and keep in mind that DELETE in Volley acts as a GET, make sure you are sending an empty body with the request.
hope that helped somehow.. happy coding