在asp.net中读取api结果

时间:2016-03-12 04:04:54

标签: c# asp.net json api

我使用下面的C#/ ASP.net代码从api获取天气数据。如果我将api链接复制/粘贴到浏览器上,则返回所有我想要的数据。 但在我的C#代码中,我收到错误" {"无法连接到远程服务器"}"

任何人都知道出了什么问题?

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

2 个答案:

答案 0 :(得分:1)

我不确定为什么你无法连接远程服务器可能会关闭你的防火墙来解决你的问题。尝试以下代码。 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();
}

答案 1 :(得分:1)

我注意到问题是我的互联网连接使用的是内部DNS服务器,由于安全限制,其设置不允许此类调用。在我们的办公室外,代码工作得很好。