c#winform怎么调用webservice

兄弟姐妹们,打扰一下,c#winform怎么调用webservice
最新回答
浪居酒家

2024-10-17 10:30:13

建议这样试试看:

亲测可用,主要还是Url的拼接,这个需要客户给出格式

  1. /// <summary>

  2. /// 与客户WMS系统通讯获取数据

  3. /// </summary>

  4. /// <param name="url">接口,需要拼接成客户规定的格式</param>

  5. /// <param name="data">请求数据,需要拼接成客户规定的Json格式</param>

  6. /// <returns>全部数据</returns>

  7. public  string Post(string url, string data)

  8. {

  9. try

  10. {

  11. //创建请求

  12. HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

  13. //设置请求方法

  14. request.Method = "Post";

  15. request.Referer = "";

  16. //将数据转换为UTF8字节流

  17. byte[] bytes = Encoding.UTF8.GetBytes(data);

  18. //设置发送的字节数

  19. request.ContentLength = bytes.Length;

  20. //设置发送内容格式

  21. request.ContentType = "application/json; charset=UTF-8";

  22. //获取用于写入请求数据的流对象

  23. Stream stream = request.GetRequestStream();

  24. //向当前流写入数据,发送请求

  25. stream.Write(bytes, 0, bytes.Length);

  26. //接收返回流,通过Web访问对象获取响应内容

  27. HttpWebResponse response = (HttpWebResponse)request.GetResponse();

  28. //通过响应内容流创建StreamReader对象

  29. //StreamReader sr = new StreamReader(request.GetRequestStream(), Encoding.UTF8);//写错,导致一直读取不了数据

  30. StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);

  31. //读取所有内容

  32. string retString = sr.ReadToEnd();

  33. //关闭流

  34. sr.Close();

  35. stream.Close();

  36. if (response != null)

  37. {

  38. //关闭响应流

  39. response.Close();

  40. }

  41. if (request != null)

  42. {

  43. //取消请求

  44. request.Abort();

  45. }

  46. return retString;

  47. }

  48. catch (Exception ex)

  49. {

  50. throw ex;

  51. }

  52. }

  53. }