远程服务器返回了一个错误:(400)错误请求
本文关键字:错误 一个 请求 服务器 返回 | 更新日期: 2023-09-27 17:51:18
我得到远程服务器返回了一个错误:(400)错误的请求错误,同时运行以下代码。我试图在http服务器上上传xml文件。我的xml文件包含用户名,密码和域的标签,当我试图连接时,我可以手动连接它,但是当我试图通过此代码连接它时,使用相同的凭据,我得到400个坏请求错误。请建议我如何克服这个问题。谢谢'
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对象的凭据属性发送用户名和密码。
400由于不正确的认证项,将抛出错误的请求错误。
- 检查您的API URL是否正确。
- 验证您的用户名和密码是否有效。输入时请检查拼写错误。
注意:主要是由于不正确的认证条目,由于拼写的变化会发生400个错误的请求。
您使用哪种类型的身份验证?使用Ben之前所说的属性发送凭据,并设置一个cookie处理程序。您已经允许重定向,检查您的web服务器,如果任何重定向发生(NTLM认证肯定)。如果有重定向,则需要存储会话,会话主要存储在会话cookie中。
//使用" ascii ";或尝试使用其他编码方案而不是"UTF8"
using (StreamWriter postStream = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.UTF8))
{
postStream.Write(postData);
postStream.Close();
}