除非fiddler正在运行,否则HttpWebRequest不起作用

dea*_*ock 22 c# httpwebrequest fiddler

这可能是我遇到的最棘手的问题.我有一段代码将POST提交到网址.当fiddler没有运行时,代码不起作用也不会抛出任何异常.但是,当fiddler运行时,代码会成功发布数据.我可以访问帖子页面,所以我知道数据是否已经过POST.这可能是非常无意义的,但这是我遇到的情况,我很困惑.

byte[] postBytes = new ASCIIEncoding().GetBytes(postData);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://myURL);
req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.224 Safari/534.10";
req.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
req.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
req.Headers.Add("Accept-Language", "en-US,en;q=0.8");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
req.CookieContainer = cc;
Stream s = req.GetRequestStream();
s.Write(postBytes, 0, postBytes.Length);
s.Close();
Run Code Online (Sandbox Code Playgroud)

Eri*_*Law 14

如果您不打电话,GetResponseStream()则无法关闭响应.如果你没有关闭响应,那么你最终会遇到状态不佳的套接字.NET.您必须关闭响应以防止干扰您以后的请求.

  • 这其实并不正确。如果您使用“using”块,您可以很好地关闭响应,无论如何,这都是您应该做的。如果不需要流,则无需调用“GetResponseStream()”。`using (var response = request.GetResponse()) { /* ... 使用响应 */ }` (2认同)

小智 7

获得HttpWebResponse后关闭.

我有同样的问题,然后我开始在每个请求后关闭响应,并且Boom,不需要让fiddler运行.

这是同步代码的伪:

request.create(url);

///codes

httpwebresponse response = (httpwebresponse)request.getresponse();

/// codes again like reading it to a stream

response.close();
Run Code Online (Sandbox Code Playgroud)


小智 5

我最近遇到了类似的问题.除非Fiddler正在运行,否则Wireshark会显示HTTPWebRequest不会离开客户端计算机.我尝试删除代理设置,但这并没有解决我的问题.我尝试了从设置请求到HttpVersion.Version10,启用/禁用SendChuck,KeepAlive以及许多其他设置.这些都没有奏效.

最后,我只是检查.Net是否检测到代理并让请求尝试忽略它.这解决了我的问题request.GetResponse()抛出一个立即异常.

IWebProxy proxy = request.Proxy;

if (request.Proxy != null)
{
    Console.WriteLine("Removing proxy: {0}", proxy.GetProxy(request.RequestUri));
    request.Proxy = null;
}
Run Code Online (Sandbox Code Playgroud)