Skip to main content
 首页 » 编程设计

c#之使用 Webclient 获取对 url 的请求会抛出异常,但如果在浏览器中打开它则工作正常

2024年06月03日40pengyingh

我有一个很奇怪的问题。我正在尝试使用 WebClient 向 url 发出获取请求

WebClient client = new WebClient();  
client.DownloadString("https://api.test.kount.net/rpc/v1/orders/detail.xml"); 

它抛出以下异常。

System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. ---> System.IO.IOException: The decryption operation failed, see inner exception. --->  
 
System.ComponentModel.Win32Exception: The message received was unexpected or badly formatted --- End of inner exception stack trace --- at System.Net.Security._SslStream.ProcessReadErrorCode(SecurityStatus errorCode, Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest,  
 
Byte[] extraBuffer) at System.Net.Security._SslStream.ProcessFrameBody(Int32 readBytes, Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)  

但是如果我在浏览器中打开这个 url,它会打开并返回一个 xml 响应。我错过了什么?有什么想法吗?

请您参考如下方法:

Right. I want to get this error message.

捕获异常并读取内容。

var responseStr = ""; 
try 
{ 
    WebClient client = new WebClient(); 
    responseStr = client.DownloadString("https://api.test.kount.net/rpc/v1/orders/detail.xml"); 
}catch(WebException wex) 
{ 
    responseStr = new StreamReader(wex.Response.GetResponseStream()).ReadToEnd(); 
} 

另一种选择

HttpClient httpClient = new HttpClient(); 
var resp = await httpClient.GetAsync("https://api.test.kount.net/rpc/v1/orders/detail.xml"); 
var status = resp.StatusCode; 
responseStr =  await resp.Content.ReadAsStringAsync(); 

所有这些都有效...