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

使用WebClient和C#,即使响应是(400)错误请求,我如何获得返回的数

发布时间:2020-12-15 03:55:23 所属栏目:百科 来源:网络整理
导读:我正在使用 Google Translate API,并尝试捕获在我获得 error时返回的数据.(FYI:我知道API密钥错了,我只是测试这个). 问题是浏览器,通过点击链接可以看到,显示错误信息,但C#抛出一个WebException,我似乎无法得到响应数据. 这是我的代码: string url = "http
我正在使用 Google Translate API,并尝试捕获在我获得 error时返回的数据.(FYI:我知道API密钥错了,我只是测试这个).

问题是浏览器,通过点击链接可以看到,显示错误信息,但C#抛出一个WebException,我似乎无法得到响应数据.

这是我的代码:

string url = "https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&source=en&target=de&q=Hello%20world";
WebClient clnt = new WebClient();

//Get string response
try
{
    strResponse = clnt.DownloadString(url);
    System.Diagnostics.Debug.Print(strResponse);
}
catch (Exception ex)
{
    System.Windows.Forms.MessageBox.Show(ex.Message);
    return null;
}

即使响应是(400)错误请求(或任何其他错误响应)),我如何获得JSON错误?我需要使用WebClient以外的其他类吗?

解决方法

这可能会帮助你
catch ( WebException exception )
{
   string responseText;

   using(var reader = new StreamReader(exception.Response.GetResponseStream()))
   {
     responseText = reader.ReadToEnd();
   }
}

这将让你得到json文本,然后你可以使用你喜欢的方法从JSON转换.

取自:Get WebClient errors as string

(编辑:李大同)

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

    推荐文章
      热点阅读