【发布时间】:2012-12-25 02:02:55
【问题描述】:
运行以下代码时,远程服务器返回错误:(400) Bad Request 错误。 我正在尝试在 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();
}
}`
【问题讨论】:
-
我怀疑它会有所不同,但您可以尝试从 URL 中删除尾随空格并使用“POST”块大写(或者必须有一个常量?)。您可以在服务器日志中看到任何内容吗?您还可以尝试在 Fiddler 中手动或通过应用程序捕获这两个请求以查找差异。不过,您的 ASPX 是否肯定接受 XML 文本的 POST?
-
不,它没有任何区别!
标签: c# .net upload httpwebrequest