422错误:Python POST请求

2024-09-25 10:24:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图对使用Eve作为框架的restapi执行一个POST请求,但是每当我试图POST我的JSON时,我会得到一个422错误,说实体无法处理。我的获取请求工作得非常好。以下是我的Eve应用程序模式:

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

^{pr2}$

以下是我如何从客户那里发出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));

Tags: nameidfalsetruenewstringvartype
1条回答
网友
1楼 · 发布于 2024-09-25 10:24:18

你让事情变得如此复杂。首先,您需要一个helper方法来调用您的服务。像这样:

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);
}

然后简单地这样称呼它:

^{pr2}$

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

相关问题 更多 >