我正在使用
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转换.
原文地址:https://www.jb51.cc/csharp/93363.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。