using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Winsoft.GOV.XF.WebApi.WXCore.Data; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Winsoft.GOV.XF.WebApi.WXCore.Services { public class WXApiService : BaseService { public WXApiService(XFDbContext context, ILoggerFactory loggerFactory, IConfigurationRoot config): base(context, loggerFactory, config) { } public async Task Notify(string openId, string msg) { Logger.LogInformation(await HttpPostAsync(_config["WXApi"] + "/api/Message", "{\"OpenId\":\"" + openId + "\",\"Content\":\"" + msg + "\"}")); } private async Task HttpPostAsync(string url, string data) { try { Logger.LogInformation(url); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); Encoding encoding = Encoding.UTF8; string param = data; byte[] bs = Encoding.UTF8.GetBytes(param.ToString()); //byte[] bs = new byte[]{}; string responseData = String.Empty; req.Method = "POST"; req.ContentType = "application/json;charset=utf-8"; req.ContentLength = bs.Length; //return; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(bs, 0, bs.Length); reqStream.Close(); } using (HttpWebResponse response = (HttpWebResponse)await req.GetResponseAsync()) { return GetResponseAsString(response); } } catch (Exception ex) { Logger.LogError("微信接口POST错误:{0}", ex.Message); return String.Empty; } } private string GetResponseAsString(HttpWebResponse rsp) { Stream stream = null; StreamReader reader = null; // 以字符流的方式读取HTTP响应 stream = rsp.GetResponseStream(); reader = new StreamReader(stream, Encoding.UTF8); return reader.ReadToEnd(); } } }