Xamarin调用WebClient.UploadValues发GET请求报System.Net.WebException错误如何解决
错误原因
- 核心原因是
WebClient.UploadValues方法的使用逻辑错误:该方法设计用于POST/PUT等需要将参数放入请求体的请求类型,你传入了GET作为请求方法,UploadValues仍然会尝试将postCollection里的参数写入请求体,但HTTP规范中GET请求不应该携带请求体,目标服务器直接拒绝了该非法请求,因此抛出异常。 - 其他可能触发该错误的场景:
- Xamarin对应平台的网络权限未配置:Android项目需要在
AndroidManifest.xml中声明INTERNET权限,iOS项目需要确保ATS(应用传输安全)配置允许访问该HTTPS域名。 - 传入的
city参数格式错误、ApiKey无效,或者本地网络不可达。
- Xamarin对应平台的网络权限未配置:Android项目需要在
修复方案
方案1:改为标准GET请求写法(推荐,适配OpenWeatherMap查询接口的要求)
将参数拼接到URL查询字符串中,使用DownloadString方法发起GET请求,代码示例:
// 对参数做转义处理避免特殊字符导致URL非法 string requestUrl = $"https://samples.openweathermap.org/data/2.5/weather?q={Uri.EscapeDataString(city)}&appid={ApiKey}"; WebClient client = new WebClient(); var result = client.DownloadString(requestUrl);
方案2:如果确实需要使用POST请求调用接口
将UploadValues的第二个参数改为"POST"即可,注意确认目标接口支持POST方式提交查询参数:
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", "POST", postCollection);
额外优化建议
WebClient已经被官方标记为过时类型,新的代码推荐使用HttpClient发起网络请求,性能和兼容性更好:
HttpClient httpClient = new HttpClient(); string requestUrl = $"https://samples.openweathermap.org/data/2.5/weather?q={Uri.EscapeDataString(city)}&appid={ApiKey}"; var response = await httpClient.GetAsync(requestUrl); // 校验请求是否成功 response.EnsureSuccessStatusCode(); string result = await response.Content.ReadAsStringAsync();
内容的提问来源于stack exchange,提问作者Nima Najafpour
相关产品推荐
相关产品推荐

