2

我正在尝试调用 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;
    }
}
4

1 回答 1

4

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

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

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

另外,你有没有试过把网址

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

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

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

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

于 2011-02-28T16:43:48.607 回答