在asp.net中调用远程Web服务

时间:2011-02-28 16:40:07

标签: c# asp.net json asmx geonames

我正在尝试调用geonames Web服务并以json格式返回我的结果。我在网上发现了一些使用httpwebrequest的教程,但在msdn中它说这已经过时了。当我的代码进入Web请求时,它会保持超时。有任何想法吗?我的.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;
    }
}

1 个答案:

答案 0 :(得分:4)

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

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

通过这种方式,您可以将JSON下载为字符串。

另外,您是否尝试过设置网址

http://api.geonames.org/postalCodeSearchJSON?placename= {0}&安培;用户名=

将您的位置放入像fiddler这样的工具 - http://www.fiddler2.com/fiddler2/

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

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

相关问题