【问题标题】:call remote web service in asp.net在 asp.net 中调用远程 Web 服务
【发布时间】:2011-07-05 21:54:33
【问题描述】:

我正在尝试调用 geonames 网络服务并以 json 格式返回我的结果。我在网上找到了一些使用 httpwebrequest 的教程,但是在 msdn 中它说这已经过时了。当我的代码到达网络请求时,它会一直超时。有任何想法吗?我的 .asmx 代码如下:

 /// Summary description for Geonames
/// </summary>
[WebService(Namespace = "http://api.geonames.org")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class Geonames : System.Web.Services.WebService
{
    private readonly static string FindCoordinates = "http://api.geonames.org/postalCodeSearchJSON?placename={0}&username=<username>";
    [WebMethod]
    [System.Web.Script.Services.ScriptMethod()]
    public string getCoordinates(string location)
    {
        Uri address = new Uri(String.Format(FindCoordinates, HttpUtility.UrlPathEncode(location)));
     //   HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(address.AbsoluteUri);
     //   wr.ProtocolVersion = HttpVersion.Version10;
        string jsonResponse = string.Empty;
        WebClient client = new WebClient();
        jsonResponse = client.DownloadString(address.AbsoluteUri);

        return jsonResponse;
    }
}

【问题讨论】:

    标签: c# asp.net json asmx geonames


    【解决方案1】:

    您是否尝试过使用它,它更简单:

            WebClient client = new WebClient();
            client.DownloadString("Your_api_location_goes_here");
    

    这样您就可以将 JSON 作为字符串下载。

    另外,你有没有试过把 URL

    http://api.geonames.org/postalCodeSearchJSON?placename={0}&username=

    将您的位置放入 fiddler 之类的工具 - http://www.fiddler2.com/fiddler2/?

    可能是服务实际上超时了,或者您构建请求的方式不太正确。这样您就可以消除它是服务还是您的代码。

    另外,您可能希望从您的问题中删除您的用户名,这样没有人可以使用您的用户名调用该服务!

    【讨论】:

    • 我在上面尝试了 webclient,但仍然出现无法连接到远程主机错误
    • 是我的工作网络弄乱了连接。当我在我的家庭网络上时,client.downloadstring 运行良好!谢谢!
    猜你喜欢
    • 2014-11-20
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 2021-09-11
    • 2014-04-03
    • 1970-01-01
    • 2020-02-26
    • 2014-03-14
    相关资源
    最近更新 更多