加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – HttpWebRequest突然停止工作,几个请求后没有收到响应

发布时间:2020-12-15 08:41:09 所属栏目:百科 来源:网络整理
导读:我正在使用 WPF .net 4.0应用程序.我有一个搜索栏.对于每个搜索令牌,我需要对8个单独的URL执行8个http请求以获取搜索结果.一旦用户停止在搜索栏中输入,我会在400毫秒后向服务器发送8个请求.搜索6到7个搜索令牌的结果非常好.但在那之后突然HttpWebRequest停止
我正在使用 WPF .net 4.0应用程序.我有一个搜索栏.对于每个搜索令牌,我需要对8个单独的URL执行8个http请求以获取搜索结果.一旦用户停止在搜索栏中输入,我会在400毫秒后向服务器发送8个请求.搜索6到7个搜索令牌的结果非常好.但在那之后突然HttpWebRequest停止了默默工作.没有例外,没有收到任何回复.我正在使用 Windows 7,我也禁用了防火墙.我不知道后续的http请求丢失在哪里.

任何人都可以向我展示灯来解决这个问题吗?

下面是我的HttpWebRequest调用代码.

public static void SendReq(string url)
{
    // Create a new HttpWebRequest object.
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

    request.ContentType = "application/x-www-form-urlencoded";
    request.Proxy = new WebProxy("192.168.1.1",8000);

    // Set the Method property to 'POST' to post data to the URI.
    request.Method = "POST";

    // start the asynchronous operation
    request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback),request);

}

private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

    // End the operation
    Stream postStream = request.EndGetRequestStream(asynchronousResult);

    string postData = this.PostData;

    // Convert the string into a byte array. 
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);

    // Write to the request stream.
    postStream.Write(byteArray,byteArray.Length);
    postStream.Close();

    // Start the asynchronous operation to get the response
    request.BeginGetResponse(new AsyncCallback(GetResponseCallback),request);
}

private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

    // End the operation
    using(HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult))
    {
        using(Stream streamResponse = response.GetResponseStream())
        {
             using(StreamReader streamRead = new StreamReader(streamResponse))
             {
                 string responseString = streamRead.ReadToEnd();
                 Debug.WriteLine(responseString);
             }
        }
    }
}

解决方法

我想我已经很晚了,但我仍然想回答你的问题,可能对别人有帮助.默认情况下,您发出的HTTP请求是HTTP 1.1请求.默认情况下,HTTP 1.1请求具有Keep-Alive连接.所以当你向同一个服务器.net框架提出太多请求时,只需要x不.请求.

你应该通过response.Close()关闭你的所有响应

您还可以指定可以同时发出的请求数.

ServicePointManager.DefaultConnectionLimit = 20;

请注意,您必须在第一个请求之前设置DefaultConnectionLimit.你可以找到更多信息
here on msdn.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读