简体   繁体   中英

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

I'm trying to send a post request to to the website NoRedInk (from this specific request post URL: https://www.noredink.com/login ). I've wrote some code, but I'm getting a "HTTP/1.1 422 Unprocessable Entity" error. Upon some research, I've found that this means the URL wasn't able to tell how to parse my payload request data.

I think I need to specify the content type (which shows up as "application/json; charset=utf-8") in my data, but I'm not quite sure the syntax of it. Here's my current code:

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

I think something more like this would work

Submit a login

Here is the userdata class

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

Now below you can set the content type and login as needed

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

}

I've seen it done this way and it should suffice for your use case. If you do not want to change. then here is an example that appears to have your almost exact same code with a solution: Problems writing a UnityWebRequest.Post

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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