call remote web service in asp.net

4.5k views Asked by At

I am trying to call the geonames web services and return my result in json format. I found some tutorials on the net that use httpwebrequest however in msdn it says that this is obsolete. When my code gets to the web request it keeps timing out. Any ideas? My .asmx code is below:

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

There are 1 answers

2
Deano On BEST ANSWER

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.

Also, Have you tried putting the URL

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

with your location into a tool like fiddler - 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!