2011-02-28 123 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