422错误:Python POST请求

时间:2017-06-04 03:49:18

标签: c# python json mongodb unity3d

我正在尝试向使用Eve作为框架的Rest API执行 POST 请求,但每当我尝试 POST 我的 JSON 我得到422错误说不可处理的实体。我的 GET 请求工作完全正常。这是我的Eve App的架构:

schema = {
    '_update': {
        'type': 'datetime',
        'minlength': 1,
        'maxlength': 40,
        'required': False,
        'unique': True,
    },
    'Name': {
        'type': 'string',
        'minlength': 1,
        'maxlength': 40,
        'required': True,
        'unique': False,
    },
    'FacebookId': {
        'type': 'integer',
        'minlength': 1,
        'maxlength': 40,
        'required': True,
        'unique': True,
    },
    'HighScore': {
        'type': 'integer',
        'minlength': 1,
        'maxlength': 40,
        'required': True,
        'unique': False,
    },
}

以下是我想发布的 JSON

{"_updated":null,"Name":"John Doe","FacebookId":"12453523434324123","HighScore":15}

以下是我尝试从客户端执行 POST 请求的方式:

IDictionary dict = Facebook.MiniJSON.Json.Deserialize(result.RawResult) as IDictionary;
string name = dict["name"].ToString();
string id = dict["id"].ToString();

Player player = new Player();
player.FacebookId = id;
player.Name = name;
player.HighScore = (int) GameManager.Instance.Points;

// Using Newtonsoft.Json to serialize
var json = JsonConvert.SerializeObject(player);

var headers = new Dictionary<string, string> {{"Content-Type", "application/json"}};

string url = "http://server.com/Players";
var encoding = new UTF8Encoding();
// Using Unity3d WWW class
WWW www = new WWW(url, encoding.GetBytes(json), headers);
StartCoroutine(WaitForRequest(www));

1 个答案:

答案 0 :(得分:1)

你让它变得如此复杂。首先,您需要一个帮助方法来调用您的服务。像这样的东西:

private static T Call<T>(string url, string body)
{
    var contentBytes = Encoding.UTF8.GetBytes(body);
    var request = (HttpWebRequest)WebRequest.Create(url);

    request.Timeout = 60 * 1000;
    request.ContentLength = contentBytes.Length;
    request.Method = "POST";
    request.ContentType = @"application/json";

    using (var requestWritter = request.GetRequestStream())
        requestWritter.Write(contentBytes, 0, (int)request.ContentLength);

    var responseString = string.Empty;
    var webResponse = (HttpWebResponse)request.GetResponse();
    var responseStream = webResponse.GetResponseStream();
    using (var reader = new StreamReader(responseStream))
        responseString = reader.ReadToEnd();

    return JsonConvert.DeserializeObject<T>(responseString);
}

然后简单地称之为:

var url = "http://server.com/Players";
var output=Call<youroutputtype>(url, json);

注意:我不知道你的输出类型是什么,所以我只想留给你。