I've seen a few of these questions on StackOverflow but I can't seem to work out why this code is not working for me.
public void postMethod(final String msg) {
String url = "http://192.168.1.30/endpoint";
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest sr = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Handle response...
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle error...
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("msg", msg);
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
queue.add(sr);
}
I'm trying to make a POST to my server which is running a python flask application. If I use a program to make HTTP Post requests my server application works fine. It will also work fine if I use an AsyncTask and do what Volley is trying to do for me.
From all of the examples I have seen this code should work fine but my flask server never receives any of the POST parameters. Any ideas what might be happening?
EDIT
Server Code:
from flask import Flask, request, abort
app = Flask(__name__)
@app.route('/endpoint', methods=['POST'])
def echo_msg():
if request.method == 'POST':
try:
msg = request.form['msg']
return msg
except KeyError, e:
# A required parameter is missing.
abort(400)
Try using the body to pass your parameters, as it's done in
JsonObjectRequest
.In
JsonObjectRequest
you can set a JSONObject as the body of the request. I'd suggest either switching you request type to this type, or overriding thegetBody()
method of yourStringRequest
similarly to the way it's done inJsonRequest
(line 93).Hope you've solved the problem. I faced a similar issue while implementing a code similar to yours. The code below actually worked for me. Thanks
}
Hope this helps anyone who ever faces such a problem. Thank you.
You can use encoded form application/x-www-form-urlencoded only this method
You need to override getBodyContentType() and return "application/x-www-form-urlencoded; charset=UTF-8";