问题描述
我的 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);