微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我的代码有错误 System.Net.WebException: '在 WebClient 请求期间发生异常

如何解决我的代码有错误 System.Net.WebException: '在 WebClient 请求期间发生异常

我的 xamarin 代码有 System.Net.WebException:“WebClient 请求期间发生异常。”错误

NameValueCollection postCollection = new NameValueCollection();
postCollection.Add("q",city);
postCollection.Add("appid",ApiKey);

WebClient postClient = new WebClient();

var postResult = postClient.UploadValues(
       "https://samples.openweathermap.org/data/2.5/weather","GET",postCollection); //this line has error

解决方法

您几乎肯定会收到以下错误:

无法发送具有此动词类型的内容正文。

这是因为 UploadValues 旨在表示 POST 或 PUT 样式的请求,因此 postCollection 被序列化为请求正文,这对于 GET 请求是不允许的。

解决此问题的最佳方法是使用 Download* 系列方法之一,例如DownloadString,用于 GET 请求:

var url = $"https://samples.openweathermap.org/data/2.5/weather?q={city}&appid={ApiKey}"
var response = postClient.DownloadString(url);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。