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)
You need to override getBodyContentType() and return "application/x-www-form-urlencoded; charset=UTF-8";
StringRequest jsonObjRequest = new StringRequest(Request.Method.POST,
getResources().getString(R.string.base_url),
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
MyFunctions.toastShort(LoginActivity.this, response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("volley", "Error: " + error.getMessage());
error.printStackTrace();
MyFunctions.croutonAlert(LoginActivity.this,
MyFunctions.parseVolleyError(error));
loading.setVisibility(View.GONE);
}
}) {
@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("username", etUname.getText().toString().trim());
params.put("password", etPass.getText().toString().trim());
return params;
}
};
AppController.getInstance().addToRequestQueue(jsonObjRequest);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With