當前位置:首頁 » 密碼管理 » winform訪問webservice

winform訪問webservice

發布時間: 2025-09-10 23:20:25

⑴ c#winform怎麼調用webservice

建議這樣試試看:

親測可用,主要還是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. }

熱點內容
java返回this 發布:2025-10-20 08:28:16 瀏覽:593
製作腳本網站 發布:2025-10-20 08:17:34 瀏覽:888
python中的init方法 發布:2025-10-20 08:17:33 瀏覽:582
圖案密碼什麼意思 發布:2025-10-20 08:16:56 瀏覽:765
怎麼清理微信視頻緩存 發布:2025-10-20 08:12:37 瀏覽:684
c語言編譯器怎麼看執行過程 發布:2025-10-20 08:00:32 瀏覽:1013
郵箱如何填寫發信伺服器 發布:2025-10-20 07:45:27 瀏覽:256
shell腳本入門案例 發布:2025-10-20 07:44:45 瀏覽:114
怎麼上傳照片瀏覽上傳 發布:2025-10-20 07:44:03 瀏覽:806
python股票數據獲取 發布:2025-10-20 07:39:44 瀏覽:713