簡體   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