gpt4 book ai didi

c# - 如何修复 400 Bad Request 错误?

转载 作者:太空狗 更新时间:2023-10-30 01:08:14 25 4
gpt4 key购买 nike

我在尝试运行我的代码时遇到了远程服务器返回错误:(400) 错误请求 错误。任何帮助,将不胜感激。谢谢。

    // Open request and set post data
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("myurl.com/restservice/Login");
request.Method = "POST";
request.ContentType = "application/json; charset:utf-8";
string postData = "{ \"username\": \"testname\" },{ \"password\": \"testpass\" }";

// Write postData to request url
using (Stream s = request.GetRequestStream())
{
using (StreamWriter sw = new StreamWriter(s))
sw.Write(postData);
}

// Get response and read it
using (Stream s = request.GetResponse().GetResponseStream()) // error happens here
{
using (StreamReader sr = new StreamReader(s))
{
var jsonData = sr.ReadToEnd();
}
}

JSON 编辑

更改为:

{ \"username\": \"jeff\", \"password\": \"welcome\" }

但还是不行。

编辑

这是我发现的有效方法:

       // Open request and set post data
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("myurl.com/restservice/Login");
request.Method = "POST";
request.ContentType = "application/json";
string postData = "{ \"username\": \"testname\", \"password\": \"testpass\" }";

// Set postData to byte type and set content length
byte[] postBytes = System.Text.UTF8Encoding.UTF8.GetBytes(postData);
request.ContentLength = postBytes.Length;

// Write postBytes to request stream
Stream s = request.GetRequestStream();
s.Write(postBytes, 0, postBytes.Length);
s.Close();

// Get the reponse
WebResponse response = request.GetResponse();

// Status for debugging
string ResponseStatus = (((HttpWebResponse)response).StatusDescription);

// Get the content from server and read it from the stream
s = response.GetResponseStream();
StreamReader reader = new StreamReader(s);
string responseFromServer = reader.ReadToEnd();

// Clean up and close
reader.Close();
s.Close();
response.Close();

最佳答案

你能试试string postData = "[{\"username\":\"testname\"},{\"password\":\"testpass\"}]";

这样你就发送了一个包含 2 个对象的数组

编辑:也许您真正想要发送的只是一个具有 2 个属性的对象,那么它将是 string postData = "{\"username\":\"testname\",\"密码\":\"testpass\"}"

关于c# - 如何修复 400 Bad Request 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10131423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com