C# Call Web Service and Get String Result


/ Published in: C#
Save to your folder(s)

Basic example of calling a web service from code using GET. You can pass parameters in as query vars.

Assumes return type of service is "String". Example return xml:


US

@SNIPPLR TEAM: Please let me put xml attributes in code sections in comments!


Copy this code and paste it in your HTML
  1. public string getServiceResult(string serviceUrl) {
  2. HttpWebRequest HttpWReq;
  3. HttpWebResponse HttpWResp;
  4. HttpWReq = (HttpWebRequest)WebRequest.Create(serviceUrl);
  5. HttpWReq.Method = "GET";
  6. HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
  7. if (HttpWResp.StatusCode == HttpStatusCode.OK)
  8. {
  9. //Consume webservice with basic XML reading, assumes it returns (one) string
  10. XmlReader reader = XmlReader.Create(HttpWResp.GetResponseStream());
  11. while (reader.Read())
  12. {
  13. reader.MoveToFirstAttribute();
  14. if (reader.NodeType == XmlNodeType.Text)
  15. {
  16. return reader.Value;
  17. }
  18. }
  19. return String.Empty;
  20. }
  21. else
  22. {
  23. throw new Exception("Error on remote IP to Country service: "+ HttpWResp.StatusCode.ToString());
  24. }
  25. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.