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



我的xamarin代码有system.net.webeexception: '在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);

最新更新