WXApiService.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using Microsoft.Extensions.Configuration;
  2. using Microsoft.Extensions.Logging;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using Winsoft.GOV.XF.WebApi.WXCore.Data;
  11. using Newtonsoft.Json;
  12. using Newtonsoft.Json.Linq;
  13. namespace Winsoft.GOV.XF.WebApi.WXCore.Services
  14. {
  15. public class WXApiService : BaseService
  16. {
  17. public WXApiService(XFDbContext context, ILoggerFactory loggerFactory, IConfigurationRoot config): base(context, loggerFactory, config)
  18. {
  19. }
  20. public async Task Notify(string openId, string msg)
  21. {
  22. Logger.LogInformation(await HttpPostAsync(_config["WXApi"] + "/api/Message", "{\"OpenId\":\"" + openId + "\",\"Content\":\"" + msg + "\"}"));
  23. }
  24. private async Task<string> HttpPostAsync(string url, string data)
  25. {
  26. try
  27. {
  28. Logger.LogInformation(url);
  29. HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
  30. Encoding encoding = Encoding.UTF8;
  31. string param = data;
  32. byte[] bs = Encoding.UTF8.GetBytes(param.ToString());
  33. //byte[] bs = new byte[]{};
  34. string responseData = String.Empty;
  35. req.Method = "POST";
  36. req.ContentType = "application/json;charset=utf-8";
  37. req.ContentLength = bs.Length;
  38. //return;
  39. using (Stream reqStream = req.GetRequestStream())
  40. {
  41. reqStream.Write(bs, 0, bs.Length);
  42. reqStream.Close();
  43. }
  44. using (HttpWebResponse response = (HttpWebResponse)await req.GetResponseAsync())
  45. {
  46. return GetResponseAsString(response);
  47. }
  48. }
  49. catch (Exception ex)
  50. {
  51. Logger.LogError("微信接口POST错误:{0}", ex.Message);
  52. return String.Empty;
  53. }
  54. }
  55. private string GetResponseAsString(HttpWebResponse rsp)
  56. {
  57. Stream stream = null;
  58. StreamReader reader = null;
  59. // 以字符流的方式读取HTTP响应
  60. stream = rsp.GetResponseStream();
  61. reader = new StreamReader(stream, Encoding.UTF8);
  62. return reader.ReadToEnd();
  63. }
  64. }
  65. }