user3033921
user3033921

Reputation: 209

Read api result in asp.net

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();
        }  
    }

Upvotes: 0

Views: 3383

Answers (2)

user3033921
user3033921

Reputation: 209

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.

Upvotes: 1

Sushil Mate
Sushil Mate

Reputation: 583

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();
}

Upvotes: 2

Related Questions