[英]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 ).我正在尝试向 NoRedInk 网站发送发布请求(来自此特定请求发布 URL: https://www.noredink.com/login )。 I've wrote some code, but I'm getting a "HTTP/1.1 422 Unprocessable Entity" error.我已经写了一些代码,但是我收到了“HTTP/1.1 422 Unprocessable Entity”错误。 Upon some research, I've found that this means the URL wasn't able to tell how to parse my payload request data.经过一些研究,我发现这意味着 URL 无法分辨如何解析我的有效负载请求数据。
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.我想我需要在我的数据中指定内容类型(显示为“application/json; charset=utf-8”),但我不太确定它的语法。 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这是用户数据 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那么这里是一个示例,它似乎具有与解决方案几乎完全相同的代码: Problems writing a UnityWebRequest.Post
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.