2010-11-02 39 views
0

我使用httpwebrequest和httpwebresponse分别发送请求和获取响应。 由于某种原因,我的连接在收到响应之前就会关闭。如何在使用httpwebrequest时保持连接直播?

这里是我的代码:

  WebRequest webRequest = WebRequest.Create (uri); 
      webRequest.ContentType = "application/x-www-form-urlencoded"; 
      webRequest.Method = "POST"; 
      byte[] bytes = Encoding.ASCII.GetBytes (parameters); 
      Stream os = null; 
      try 
      { // send the Post 
       webRequest.ContentLength = bytes.Length; //Count bytes to send 
       os = webRequest.GetRequestStream(); 
       os.Write (bytes, 0, bytes.Length);   //Send it 
      } 
      catch (WebException ex) 
      { 
       MessageBox.Show (ex.Message, "HttpPost: Request error", 
       MessageBoxButtons.OK, MessageBoxIcon.Error); 
      } 

      try 
      { // get the response 
       WebResponse webResponse = webRequest.GetResponse(); 
       if (webResponse == null) 
       { return null; } 
       StreamReader sr = new StreamReader (webResponse.GetResponseStream()); 
       return sr.ReadToEnd().Trim(); 
      } 
      catch (WebException ex) 
      { 
       MessageBox.Show (ex.Message, "HttpPost: Response error", 
       MessageBoxButtons.OK, MessageBoxIcon.Error); 
      } 
      return null; 
     } 

错误:

alt text

+0

几乎看不到错误信息。如果连接超时,请检查您的Web服务器(或J2EE服务器)配置文件。 – exiter2000 2010-11-02 20:05:42

+0

错误:远程服务器返回错误。(500)内部服务器错误。 – BumbleBee 2010-11-02 20:10:24

+0

当我看着堆栈,我看到连接:关闭 – BumbleBee 2010-11-02 20:10:42

回答

1

默认情况下,如果使用的是HTTP/1.1协议,则假定的连接被保持活,除非服务器决定另外指示(使用Connection:close标题)。

在你的情况,你有一个服务器拒绝与500错误的请求。你应该调查为什么会发生这种情况。您不应该担心连接:此时关闭标题。即使服务器关闭连接,客户端也会在下次打开新连接时正常处理该连接。

总而言之,来自服务器的500响应不是由于连接被关闭。这是因为服务器不喜欢你发送的请求。

+0

谢谢Feroze。 – BumbleBee 2010-11-02 20:44:27

0

如果会话超时错误(我不能看到错误消息),你应该有配置参数,如下面的您的Web服务器或J2EE服务器。

下面是从Tomcat的web.xml

<session-config> 
    <session-timeout>30</session-timeout> 
</session-config> 
+0

我想从我的Windows应用程序中使用Web服务。 – BumbleBee 2010-11-02 20:16:50

+0

我不知道我如何能够在网络服务器上设置会话超时 – BumbleBee 2010-11-02 20:21:25