我刚遇到以下问题:
我需要下载登录页面后面的数据。但是,当我发出 get 请求时,服务器正在提供错误数据 - 内容在那里,但标头集中没有内容长度,它是一个空字段。我用 Fiddler 查找了它,当我尝试用浏览器下载文件时,它也是一样的,但是浏览器完成了下载,而 C# 在从我的请求中获取响应对象时出现异常。
标题如下所示:
HTTP/1.1 200 OK
Date: Sat, 06 Dec 2014 11:55:06 GMT
Server: Apache
Content-Disposition: attachment; filename=;
Pragma: no-cache
Expires: 0
Content-Length:
X-Powered-By: PleskLin
Connection: close
Content-Type: application/octet-stream
Hersteller;"Hersteller Art-Nr";"Lieferant Art-Nr";Ma�stab;Bezeichnung;EAN;"EK (netto)";UVP;USt;Verkaufseinheit;Hinweis;"Letzte Pro...
我的代码看起来像这样
public string ReadPage(string path, string method = "GET"){
var result = "";
var request = (HttpWebRequest)WebRequest.Create(path);
request.Method = method;
request.Host = "somehost.de";
request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
request.Referer = @"http://somehost.de/login.php?redir=list.php%3Ftype%3Dmm";
request.AllowAutoRedirect = true;
request.Headers.Add("Cookie", LoginCookie);
try
{
var response = request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
result = sr.ReadToEnd();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
//throw;
}
return result;
}
异常出现在该var response = request.GetResponse();
行中。知道如何解决这个问题吗?我只想让它继续,让我读出数据。
忘记了异常 - 它是带有消息的 WebException 服务器违反了协议。Section=ResponseHeader Detail='Content-Length' 标头值无效