繁体   English   中英

在 C# 中发出 post 请求时如何指定 content-type?

[英]How do I specify the content-type when making a post request in C#?

我正在尝试向 NoRedInk 网站发送发布请求(来自此特定请求发布 URL: https://www.noredink.com/login )。 我已经写了一些代码,但是我收到了“HTTP/1.1 422 Unprocessable Entity”错误。 经过一些研究,我发现这意味着 URL 无法分辨如何解析我的有效负载请求数据。

我想我需要在我的数据中指定内容类型(显示为“application/json; charset=utf-8”),但我不太确定它的语法。 这是我当前的代码:

private void Start()
{
    StartCoroutine(Upload());
}

IEnumerator Upload()
{
    WWWForm form = new WWWForm();
    form.AddField("login_name", "my_username");
    form.AddField("lti_context", "null");
    form.AddField("password", "my_password");
    //form.AddField("Content-Type", "application/json"); (this is what I tried that didn't work)

    using (UnityWebRequest www = UnityWebRequest.Post("https://www.noredink.com/login", form))
    {
        yield return www.SendWebRequest();

        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.Log(www.error); // this is where I get the 422 error
        }
        else
        {
            print(www.downloadHandler.text)
        }
    }
}

我认为更像这样的东西会起作用

提交登录

这是用户数据 class

public class UserData 
{
    public string username;
    public string password;
}

现在在下面您可以根据需要设置内容类型和登录

public IEnumerator Login(string username, string password)
{
    var user = new UserData();
    user.username = username;
    user.password = password;

    string json = JsonUtility.ToJson(user);

    var req = new UnityWebRequest("https://www.noredink.com/login", "POST");
    byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json);
    req.uploadHandler = (UploadHandler)new UploadHandlerRaw(jsonToSend);
    req.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
    req.SetRequestHeader("Content-Type", "application/json");

    //Send the request then wait here until it returns
    yield return req.SendWebRequest();

    if (req.isNetworkError)
    {
        Debug.Log("Error While Sending: " + req.error);
    }
    else
    {
        Debug.Log("Received: " + req.downloadHandler.text);
    }

}

我已经看到它这样做了,它应该足以满足您的用例。 如果你不想改变。 那么这里是一个示例,它似乎具有与解决方案几乎完全相同的代码: Problems writing a UnityWebRequest.Post

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM