422错误:Python的POST请求
问题描述:
我试着做一个POST请求,这是使用夏娃为骨架我的REST API,但是每当我试图POST我JSON我得到一个422错误说无法处理的实体。我的GET请求工作得很好。这是我为我的夏娃应用模式:422错误:Python的POST请求
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));
答
你让它变得如此复杂。起初你需要一个辅助方法来调用你的服务。是这样的:
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);
注:我不知道什么是你的输出类型,所以我就交给你了。