排球的POST请求 [英] POST request with Volley

查看:51
本文介绍了排球的POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个基本的移动应用程序以与nosql数据库进行交互.到目前为止,使用Volley并没有任何问题.我的数据库中有两个主要实体,并且两个实体都将所有属性存储为字符串.对于一个实体,Volley的GET和POST可以正常工作,但是对于另一个实体,GET请求有效,但POST请求无效(某些参数为null).

I'm making a basic mobile app to interact with a nosql database. So far, I've had no problems using Volley. I have two main entities in my database, and both are storing all of their attributes as strings. With one entity, Volley's GET and POST works fine, but with the other entity, the GET request works but not the POST request (some parameters are null).

我遇到问题的页面旨在让用户编辑他/她已经放入的数据.我首先用Volley GET请求填充该页面.一切正常,所有参数都可以正确显示.然后,如果用户更改了数据并提交了数据,则会通过POST请求提交数据,该请求失败,因为某些参数为空.

The page I'm having trouble with is intended to let the user edit data he/she has already put in. I first populate it with a Volley GET request. That works fine, and all of the parameters display properly. Then, if the user alters the data and submits it, it is submitted with a POST request, which fails because some of the parameters are null.

我已经将错误缩小到(我认为)了getParams()函数.将填充generals和victors变量,但所有其他变量返回为null.同样,我所有的变量都是字符串,因此它看起来不像是不兼容的数据类型.

I've narrowed the error down (I think) to the getParams() function. The generals and victors variables are populated, but all of the others come back as null. Again, all of my variables are strings, so it doesn't seem like an incompatible data type.

这是我的代码:

    RequestQueue queue = Volley.newRequestQueue(this);

    StringRequest postRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    if (response != null) {
                        try {
                            Toast.makeText(EditDeleteDetail.this, "Detail Updated", Toast.LENGTH_LONG).show();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    Log.e(TAG, response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                }
            }
    ) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();

            params.put("generals", generals);
            Log.d("Params generals", generals);
            params.put("victor", victor);
            Log.d("Params victor", victor);
            params.put("ramifications", ramifications);
            Log.d("Params ramifications", ramifications);
            params.put("casualties", casualties);
            Log.d("Params casualties", casualties);
            params.put("startdate", startdate);
            Log.d("Params startdate", startdate);
            params.put("enddate", enddate);

            return params;
        }
    };
    queue.add(postRequest);

    return true;
}

这是API的代码,这是我在Python中完成的.我可以使用卷曲测试或Postman应用程序手动进行POST,所有数据都已正确填充并保存在数据库中:

Here's the code for the API, which I did in Python. I can manually POST using curl tests or the Postman app, and all of the data is correctly populated and saved in the database:

import webapp2
from google.appengine.ext import ndb
import db_models
import json

class Detail(webapp2.RequestHandler):
def post(self, **kwargs):
    """Creates a Detail entity

    POST Body Variables:
    generals- String. List of commanding generals
    victor - String. Winner (if any) of battle
    ramifications - String. Results and implications of the battle
    casualties - Stored as string, but also includes integers.  Participating armies' casualties
    startdate - Date property
    enddate - Date property
    """
    if 'application/json' not in self.request.accept:
        self.response.status = 406
        self.response.status_message = "Not Acceptable, API only supports application/json MIME type"
        return
    if 'did' in kwargs:
        curr_det = ndb.Key(db_models.Details, int(kwargs['did'])).get()
        generals = self.request.get('generals', default_value=None)
        victor = self.request.get('victor', default_value=None)
        ramifications = self.request.get('ramifications', default_value=None)
        casualties = self.request.get('casualties', default_value=None)
        startdate = self.request.get('startdate', default_value=None)
        enddate = self.request.get('enddate', default_value=None)
        if generals:
            curr_det.generals = generals
        if victor:
            curr_det.victor = victor
        if ramifications: 
            curr_det.ramifications = ramifications
        if casualties:
            curr_det.casualties = casualties
        if startdate:
            curr_det.startdate = startdate
        if enddate:
            curr_det.enddate = enddate
        curr_det.put()
        out = curr_det.to_dict()
        self.response.write(json.dumps(out))

    else: 
        new_detail = db_models.Details()  #making a new Detail
        generals = self.request.get('generals', default_value=None)
        victor = self.request.get('victor', default_value=None)
        ramifications = self.request.get('ramifications', default_value=None)
        casualties = self.request.get('casualties', default_value=None)
        startdate = self.request.get('startdate', default_value=None)
        enddate = self.request.get('enddate', default_value=None)
        if generals:
            new_detail.generals = generals
        else:
            self.response.status = 400
            self.response.status_message = "Invalid request, Commanding generals are Required"
            return
        if victor:      
            new_detail.victor = victor
        if ramifications:
            new_detail.ramifications = ramifications
        if casualties:
            new_detail.casualties = casualties
        if startdate:
            new_detail.startdate = startdate
        if enddate:
            new_detail.enddate = enddate    
        key = new_detail.put()  #this saves the new Detail in the database
        out = new_detail.to_dict()      #then we return the thing we just made
        self.response.write(json.dumps(out))
        return

推荐答案

为您的案例尝试其他语法和请求类型:

Try a different syntax and Request type for your case:

 Map<String, Object> jsonParams = new ArrayMap<>();
jsonParams.put("nodeId", null);
jsonParams.put("userId", null);
jsonParams.put("email", "some@gmail.com");
jsonParams.put("userProfile", null);
jsonParams.put("region", null);
jsonParams.put("password", 123);
jsonParams.put("places", new ArrayList());

JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(jsonParams),
        new Response.Listener<JSONObject>()
        {
            @Override
            public void onResponse(JSONObject response)
            {
              //print it here and check
            }
        },
        new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                if (null != error.networkResponse)
                {
                 //do whatever
                }
            }
        });

这篇关于排球的POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆