Posted By

jasonseney on 06/01/09


Tagged

c webservice


Versions (?)

Who likes this?

9 people have marked this snippet as a favorite

moneypenny
paelgr
jimfred
umang_nine
emregulcan
uday1302
hinesnetwork
rageit
Priestd09


C# Call Web Service and Get String Result


 / Published in: C#
 

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:

<?xml>
<string>US</string>

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

  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  

You need to login to post a comment.