Get request to a url throws exception using Webclient but works fine if open it in browser

房东的猫 提交于 2019-12-11 11:44:27

问题


I have very strange issue. I am trying to make a get request to a url using WebClient

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

It throws following exception.

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) 

But if I open this url in browser, it opens and return a xml response. What am I missing? Any ideas?


回答1:


Right. I want to get this error message.

Catch the exception and read the content.

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();
}

One more alternative

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();

All of them works...



来源:https://stackoverflow.com/questions/31629206/get-request-to-a-url-throws-exception-using-webclient-but-works-fine-if-open-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!