首页 > 解决方案 > Android - 将正文添加到 StringRequest 时来自 Flask 的 Volley 错误 400

问题描述

如果我发送没有正文的请求,一切正常。无论如何,当我添加正文时,我得到错误 400。正文被JSON转换为String.

要求:

StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        key=response;
    }
 }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(),"Fail database",Toast.LENGTH_SHORT).show();
            Log.d("tuzzo","err: "+error);
        }
   }
}){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            params.put("Content-Type", "application/json");
            return params;
        }

        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            SimpleDateFormat myFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.ITALY);
            Map<String, String> params = new HashMap<>();
            params.put("nameEx", String.valueOf(prefs.getString("exhtitle",null)));
            params.put("descrEx", String.valueOf(prefs.getString("exhdescr",null)));
            params.put("longDescr", String.valueOf(longdescr.getText()));

            params.put("idCategories", String.valueOf(catmap.get(String.valueOf(spin_cat.getText()).toLowerCase())));
            try {
                params.put("startDate", myFormat.format(myFormat.parse(startDate.getText().toString())));
                params.put("endDate", myFormat.format(myFormat.parse(endDate.getText().toString())));
            }catch (ParseException e){
                Log.e("testdate","error: "+e);
            }
            params.put("idMuseums", String.valueOf(musmap.get(String.valueOf(spin_mus.getText()).toLowerCase())));
            params.put("chiave", String.valueOf(prefs.getString("exhkey",null)));
            return params;
        }
        @Override
        public byte[] getBody() throws AuthFailureError {
            try {
                return full == null ? null : full.getBytes("utf-8");
            } catch (UnsupportedEncodingException uee) {
                Log.d("volleyuee", "uee: "+uee);
                return null;
            }
        }
        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }
    };

我在 Python 中使用 Flask 的服务器:

def upd():
data = request.data

if not os.path.exists("/home/tuzzo/stg/res/%s"%request.form['chiave']):
    os.makedirs("/home/tuzzo/stg/res/%s"%request.form['chiave'])
    os.makedirs("/home/tuzzo/stg/res/%s/download"%request.form['chiave'])
    os.makedirs("/home/tuzzo/stg/res/%s/header"%request.form['chiave'])
    if not data is None:
        with open('/home/tuzzo/stg/res/%s/download/jsonEx.json'%request.form['chiave'], 'w') as outfile:
            simplejson.dump(data, outfile)
        with open('/home/tuzzo/stg/res/%s/manifest.xml'%request.form['chiave'], 'w') as xmlfile:
            xmlfile.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?><channel><item><json>http://tuzzo.pythonanywhere.com/download/"+request.form['chiave']+"/jsonEx.json</json></item></channel>")
    addEx(request.form['chiave'])
    return request.form['chiave']

如果我发送Stringin 参数并且我使用data = request.form[value]它可以工作,但我不知道这个请求中缺少什么。

标签: androidpythonflaskandroid-volleypythonanywhere

解决方案


默认情况下,Flask 视图只响应 GET 请求,除非您有一个路由装饰器指定它们也应该响应 POST(或任何其他类型)。像这样:

@app.route('/something', methods=['GET', 'POST'])
def view():
   ... view code ...

推荐阅读