简体   繁体   English

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

[英]call remote web service in asp.net

I am trying to call the geonames web services and return my result in json format. 我正在尝试调用地名Web服务,并以json格式返回我的结果。 I found some tutorials on the net that use httpwebrequest however in msdn it says that this is obsolete. 我在网上找到了一些使用httpwebrequest的教程,但是在msdn中它说这已经过时了。 When my code gets to the web request it keeps timing out. 当我的代码到达网络请求时,它会一直超时。 Any ideas? 有任何想法吗? My .asmx code is below: 我的.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;
    }
}

Have you tried using this instead, its a lot simpler: 您是否尝试过使用它,它要简单得多:

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

That way you can download the JSON as a string. 这样,您可以将JSON下载为字符串。

Also, Have you tried putting the URL 另外,您是否尝试过输入网址

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

with your location into a tool like fiddler - http://www.fiddler2.com/fiddler2/ ? 将您的位置放到提琴手之类的工具中-http: //www.fiddler2.com/fiddler2/

It could be that the service is actually timing out, or the way you are building the request isnt quite right. 可能是服务实际上正在超时,或者您构建请求的方式不太正确。 That way you could eliminate whether it is the service or your code. 这样,您可以消除是服务还是代码。

Also, you might want to remove your username from your question, just so that no-one can call the service using your username! 另外,您可能想从问题中删除用户名,只是没有人可以使用您的用户名致电服务!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM