GetReponse()上的“底层连接已关闭:发送时发生意外错误”但不通过浏览器

问题描述:

我试图利用使用GET方法的REST服务。我正在使用.Net Framework 4.5.2。我在下面写的只是一个测试,看看我是否可以实际提出请求。如果我把URL直接放到浏览器中,我会以json格式的字符串数据得到很好的回应。但是当我尝试运行代码时,我最终得到了以下错误:GetReponse()上的“底层连接已关闭:发送时发生意外错误”但不通过浏览器

“底层连接已关闭:发送时出现意外错误。” InnerException = {“无法从传输连接读取数据:现有连接被远程主机强制关闭。”}

我试过设置keepalive为true和false,我试过使用WebClient以及DownloadString太....都导致相同的错误。有没有人知道我错过了什么?或者这是服务器端的某种问题?

Dim script As String = "236" 
Dim deploy As String = "1" 
Dim compid As String = "915960_SB2" 
Dim h As String = "value1" 
Dim id As String = "1241389" 
Dim status As String = "in freezer" 
Dim request As HttpWebRequest 
Dim response As HttpWebResponse 

Try 

'I have removed the real website name from this code. 
      Dim theurl As String = "https://website/app/site/hosting/scriptlet.nl?script={0}&deploy={1}&compid={2}&h={3}&Id={4}&Status={5}" 
      Dim url As String = String.Format(theurl, script, deploy, compid, h, id, status) 

      request = HttpWebRequest.Create(url) 
      request.Method = "GET" 
      request.ContentType = "application/json" 

'This is where the error occurs 
      response = request.GetResponse() 

Catch ex As Exception 
      Dim test as string="" 
Finally 

End Try 
+0

我推荐使用的工具像Fiddler检查HTTP流量,看看是否有您的浏览器请求和你的代码之间的差异。一个小问题:'Content-Type:application/json'对GET请求没有任何意义。你可能会想'Accept:application/json'。 –

+0

嗯,我解决了它..我偶然发现了其他人建议尝试设置安全协议。所以在我的代码的顶部,并写下这一行:ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12,它的工作。 –

我解决了它。我偶然发现了其他人遇到同样问题的下列网站。

http://www.avivroth.com/2013/05/02/rest-calls-in-net-c-over-ssl-https/

的解决方案是设置的安全协议。我刚刚从ssl到tls11,然后到tls12,发现最后一个工作。

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12