gpt4 book ai didi

c# - HttpWebRequest-远程服务器返回错误 : (400) Bad Request

转载 作者:太空狗 更新时间:2023-10-29 18:18:43 28 4
gpt4 key购买 nike

我正在运行以下代码时收到远程服务器返回错误:(400) 错误请求错误。我正在尝试在 http 服务器上上传 xml 文件。我的 xml 文件包含用户名、密码和域的标记,当我尝试手动连接时,我能够连接它,但是当我尝试通过此代码连接它时使用相同的凭据,我收到 400 Bad Request 错误.请建议我如何克服这个问题。谢谢 `

  public static void UploadHttp(string xml)     
{

string txtResults = string.Empty;
try
{
string url = "http://my.server.com/upload.aspx ";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.KeepAlive = false;
request.SendChunked = true;
request.AllowAutoRedirect = true;
request.Method = "Post";
request.ContentType = "text/xml";
var encoder = new UTF8Encoding();
var data = encoder.GetBytes(xml);
request.ContentLength = data.Length;
var reqStream = request.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
WebResponse response = null;
response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var str = reader.ReadToEnd();
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
HttpWebResponse err = ex.Response as HttpWebResponse;
if (err != null)
{
string htmlResponse = new StreamReader(err.GetResponseStream()).ReadToEnd();
txtResults = string.Format("{0} {1}", err.StatusDescription, htmlResponse);
}
}
else
{

}
}
catch (Exception ex)
{
txtResults = ex.ToString();
}
}`

最佳答案

您确定应该使用 POST 而不是 PUT 吗?

POST 通常与 application/x-www-urlencoded 格式一起使用。如果您使用的是 REST API,您也许应该使用 PUT?如果您要上传文件,您可能需要使用 multipart/form-data。并非总是如此,但通常情况下,这是正确的做法。

此外,您似乎没有使用凭据登录 - 您需要使用 HttpWebRequest 对象的 Credentials 属性来发送用户名和密码。

关于c# - HttpWebRequest-远程服务器返回错误 : (400) Bad Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14262072/

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