我在StackOverflow上看到了一些这样的问题,但我似乎无法弄清楚为什么这段代码对我不起作用. public void postMethod(final String msg) { String url = "http://192.168.1.30/endpoint"; RequestQueue queue = Volley.new
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);
}
我正在尝试对运行python flask应用程序的服务器发出POST.如果我使用程序来发出HTTP Post请求我的服务器应用程序工作正常.如果我使用AsyncTask并且做了Volley试图为我做的事情,它也会正常工作.
从我看到的所有示例中,此代码应该可以正常工作,但我的烧瓶服务器永远不会收到任何POST参数.有什么想法可能会发生什么?
编辑
服务器代码:
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)
你需要覆盖getBodyContentType()并返回“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);
