我遇到了以下问题:
我需要下载登录页面后面的数据。然而,当我提出我的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'标头值无效
答案 0 :(得分:0)
稍微改变
public static class WebRequestExtensions
{
public static WebResponse GetWEResponse(this WebRequest request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
try
{
return request.GetResponse();
}
catch (WebException e)
{
return e.Response;
}
}
}
您现在可以使用request.GetWEResponse
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.GetWEResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
result = sr.ReadToEnd();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
//throw;
}
return result;
}
或更好
public string ReadPage(string path, string method = "GET")
{
var request = (HttpWebRequest)WebRequest.Create(path);
request.Method = method;
request.Host = "somehost.de";
request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
request.Referer = @"http://somehost.de/login.php?redir=list.php%3Ftype%3Dmm";
request.AllowAutoRedirect = true;
request.Headers.Add("Cookie", LoginCookie);
using (var response = (HttpWebResponse)request.GetWEResponse())
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}