0

I am using the below C#/ASP.net code to get the weather data from the api. The api link works if I copy/paste it on the browser, returns all the data I want . But in my C# code, I get error "{"Unable to connect to the remote server"}"

Anyone knows what is wrong?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using System.Runtime.Serialization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Xml;

namespace WebApplication2
{
    public partial class GetData : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        [System.Web.Services.WebMethod]
        public static  void getData()
        {


            var url = "http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=e67fab67a2bc61c221e8a6165965c107";
            var client = new HttpClient();

            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            var response = client.GetAsync(url).Result;

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            getData();
        }  
    }
INDIA IT TECH
  • 1,902
  • 4
  • 12
  • 25
user3033921
  • 189
  • 1
  • 8
  • 21

2 Answers2

2

I'm not sure why you getting unable to connect remote server may be turning off your firewall solve your problem. try below code. https://stackoverflow.com/a/16642279/2745294 https://stackoverflow.com/a/5566981/2745294

string urlAddress = "http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=e67fab67a2bc61c221e8a6165965c107";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

if (response.StatusCode == HttpStatusCode.OK)
{
  Stream receiveStream = response.GetResponseStream();
  StreamReader readStream = null;

  if (response.CharacterSet == null)
  {
     readStream = new StreamReader(receiveStream);
  }
  else
  {
     readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
  }

  string data = readStream.ReadToEnd();

  response.Close();
  readStream.Close();
}
Community
  • 1
  • 1
Sushil Mate
  • 583
  • 6
  • 14
1

I noticed the issue was that my internet connection was using an internal dns server which its setting does not allow such a calls due to security restrictions. Outside our office, the code works just fine.

user3033921
  • 189
  • 1
  • 8
  • 21