using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using Microsoft.Extensions.Primitives; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace ET.Server { public static class HttpHelper { public static async ETTask GetBodyParameter(HttpListenerContext context) { return await new StreamReader(context.Request.InputStream).ReadToEndAsync(); } public static void Response(HttpListenerContext context, object response) { byte[] bytes = JsonHelper.ToJson(response).ToUtf8(); context.Response.StatusCode = 200; context.Response.ContentEncoding = Encoding.UTF8; context.Response.ContentLength64 = bytes.Length; context.Response.OutputStream.Write(bytes, 0, bytes.Length); } /// /// post请求抖音接口 /// /// /// /// /// public static string PostRequestByDouyin(string url, Dictionary heads, JObject param) { if (string.IsNullOrEmpty(url) || param is not { Count: > 0 }) { return null; } using HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Accept.TryParseAdd("application/json"); // 设置请求头 if (heads is { Count: >= 0 }) { foreach (var head in heads) { httpClient.DefaultRequestHeaders.Add(head.Key, head.Value); } } // post HttpContent content = new StringContent(JsonConvert.SerializeObject(param), Encoding.UTF8, "application/json"); // response HttpResponseMessage response = httpClient.PostAsync(new Uri(url), content).Result; if (response.IsSuccessStatusCode) { return response.Content.ReadAsStringAsync().Result; } string statusCode = response.StatusCode.ToString(); Log.Debug($"http请求错误...statusCode:{statusCode}, url:{url}"); return null; } /// /// get请求抖音接口 /// /// /// /// /// public static string GetRequestByDouyin(string baseUrl, Dictionary heads, Dictionary param) { if (string.IsNullOrEmpty(baseUrl) || param is not { Count: > 0 }) { return null; } using HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Accept.TryParseAdd("application/json"); // 设置请求头 if (heads is { Count: >= 0 }) { foreach (var head in heads) { httpClient.DefaultRequestHeaders.Add(head.Key, head.Value); } } StringBuilder url = new StringBuilder(baseUrl); if (param is { Count: >= 0 }) { url.Append('?'); List keyList = new List(param.Keys); for (int i = 0; i < param.Count; i++) { url.Append(keyList[i]).Append('=').Append(param[keyList[i]]); if (i < param.Count) { url.Append('&'); } } } HttpResponseMessage response = httpClient.GetAsync(new Uri(url.ToString())).Result; if (response.IsSuccessStatusCode) { return response.Content.ReadAsStringAsync().Result; } string statusCode = response.StatusCode.ToString(); Log.Debug($"http请求错误...statusCode:{statusCode}, url:{url}"); return null; } } }