【问题标题】:Read api result in asp.net在 asp.net 中读取 api 结果
【发布时间】:2016-06-27 11:43:13
【问题描述】:

我正在使用下面的 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();
        }  
    }

【问题讨论】:

    标签: c# asp.net json api


    【解决方案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();
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2014-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-10
        • 1970-01-01
        • 2021-11-12
        相关资源
        最近更新 更多