2011-02-28 136 views
2

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

/// 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

您是否尝试过用这个代替,其简单了很多:

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

这样,你可以下载JSON作为一个字符串。

此外,你试过把URL

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

您的位置到像小提琴手的工具 - http://www.fiddler2.com/fiddler2/

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

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

+0

我试过上面的webclient,我仍然无法连接到远程主机错误 – rbur0425 2011-02-28 19:28:30

+1

这是我的工作网络搞乱了连接。当我在我的家庭网络client.downloadstring工作正常!谢谢! – rbur0425 2011-03-01 14:35:42