Search code examples
c#apixamarinsystem.net.webexception

my code has error System.Net.WebException: 'An exception occurred during a WebClient request.'


my xamarin code has System.Net.WebException: 'An exception occurred during a WebClient request.' error

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

Solution

  • You are almost certainly getting the following error:

    Cannot send a content-body with this verb-type.

    This is because UploadValues is intended to represent a POST or PUT style request, so postCollection gets serialized as a request body, which is not permitted for a GET request.

    The best way to fix is this is to use one of the Download* family of methods, e.g. DownloadString, which are intended to be used for GET requests:

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