【问题标题】:my code has error System.Net.WebException: 'An exception occurred during a WebClient request.' [closed]我的代码有错误 System.Net.WebException:“WebClient 请求期间发生异常。” [关闭]
【发布时间】:2021-10-03 12:27:58
【问题描述】:

我的 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

【问题讨论】:

  • 您需要检查 Exception 对象以确定根本原因是什么

标签: c# api xamarin system.net.webexception


【解决方案1】:

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

无法发送具有此动词类型的内容主体。

这是因为 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多