02 December 2011

C# - Calling a web service with GET or POST

For a dashboard I needed to connect to a Google web service and retrieve data from it. I was working in Silverlight, but Silverlights security model did not allow me to call Googles web service, so I called from an ASP.NET web service as follows:
[WebMethod]
public WebServiceResponse CallService(string name,
                                      string url,
                                      string method,
                                      string contentType,
                                      string postData) {
  WebServiceResponse result = new WebServiceResponse();
  try{
    //Convert the post data into a byte array
    //The post data is a string like "username=EGS&password=305"
    byte[] data = null;
    if (!string.IsNullOrEmpty(postData))
      data = Encoding.UTF8.GetBytes(postData);

    //Create the request and write the post data to it if any
    WebRequest request = WebRequest.Create(url);
    if (!string.IsNullOrEmpty(method))
      request.Method = method;
    if (!string.IsNullOrEmpty(contentType))
      request.ContentType = contentType;
    if (data != null) {
      request.ContentLength = (long)data.Length;
      using (Stream stream = request.GetRequestStream())
        stream.Write(data, 0, data.Length);
    }
    else
      request.ContentLength = 0L;

    //Get the response from the web service
    using (WebResponse response = request.GetResponse())
    using (StreamReader reader =
           new StreamReader(response.GetResponseStream())) {
      result.StatusCode =
             (int)(response as HttpWebResponse).StatusCode;
      result.StatusDescription =
             (response as HttpWebResponse).StatusDescription;
      result.Content = reader.ReadToEnd();
    }
  }
  catch (Exception ex) {
    result.Error = "Error: [DashboardService.CallService] " + ex.Message;
  }
  return result;
}
WebServiceResponse is a custom class with the properties StatusCode, StatusDescription, Content and Error.

No comments:

Post a Comment