Httphelper: Http请求webapi小记
文章目录
- 1、HttpHelper.cs Framework4.81
- 2、HttpHelper.cs NET8
- 3、JsonHelper.cs Framework4.81
- 4、JsonHelper.cs NET8
- 5、uniapp request.js 访问WEBAPI
每次查找、测试都比较费事,记录一下把
1、HttpHelper.cs Framework4.81
using System;
using System.IO;
using System.Net;
using System.Text;
namespace ClassLibrary
{public static class HttpHelper{public static string ApiUrl = "http://localhost:6666/api/Data/";/// <summary>/// 执行HTTP GET请求。/// </summary>/// <param name="url">目标URL。</param>/// <param name="timeoutMilliseconds">请求超时时间(毫秒)。</param>/// <param name="proxy">可选参数:指定代理服务器地址。</param>/// <returns>返回响应的内容作为字符串。</returns>public static string Get(string Method, int timeoutMilliseconds = 10000, IWebProxy proxy = null){try{string url = ApiUrl + Method;HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);request.Method = "GET";request.Timeout = timeoutMilliseconds;if (proxy != null){request.Proxy = proxy;}using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)){return reader.ReadToEnd();}}catch (Exception ex){throw ex;}}/// <summary>/// 执行HTTP POST请求。/// </summary>/// <param name="url">目标URL。</param>/// <param name="postData">POST数据(通常为JSON或表单编码的数据)。</param>/// <param name="contentType">内容类型,默认为"application/json"。</param>/// <param name="timeoutMilliseconds">请求超时时间(毫秒)。</param>/// <param name="proxy">可选参数:指定代理服务器地址。</param>/// <returns>返回响应的内容作为字符串。</returns>public static string Post(string Method, string postData, int timeoutMilliseconds = 10000, IWebProxy proxy = null){try{string url = ApiUrl + Method;HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);request.Method = "POST";request.ContentType = "application/json";request.ContentLength = Encoding.UTF8.GetByteCount(postData);request.Timeout = timeoutMilliseconds;if (proxy != null){request.Proxy = proxy;}using (StreamWriter writer = new StreamWriter(request.GetRequestStream())){writer.Write(postData); }using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())using (StreamReader reader = new StreamReader(response.GetResponseStream())){return reader.ReadToEnd(); // 返回服务器响应内容}}catch (Exception ex){throw ex;}}}
}
调用读取示例
//传输modelpublic class DataReq{public string Data { get; set; }public string DBstr { get; set; }}public class object1{public string str { get; set; }}/* public class object2{public string ID { get; set; }public string Name{ get; set; }}*///客户端发送请求public void testpost(){DataReq r = new DataReq();r.Data = "[{\"str\":\"321\"},{\"str\":\"\"}]";r.DBstr = "123";//"{\"DBstr\":\"321\",\"Data\":\"\"}"string postData= JsonHelper.Serialize(r);string method = "GetTest";string rst = HttpHelper.Post(method, postData);}//webapi接受请求[Route("api/[controller]/[action]")][ApiController]public class DataController : ControllerBase{[HttpPost]public async Task<IActionResult> GetTest(DataReq obj){List<object1> LIST = new List<object1>();if (!String.IsNullOrEmpty(obj.Data))LIST = JsonHelper.ToObj<List<object1>>(obj.Data);//解析数据//省略逻辑DataTable dt = ;//查询if (dt.Rows.Count == 0) return Ok("no");string JsonStr = JsonHelper.ToStr(dt);return Ok(JsonStr);}}
2、HttpHelper.cs NET8
using System.Net;
using System.Text;
using System.Text.Json;/// <summary>
/// http帮助类
/// </summary>
public class HttpHelper
{private readonly HttpClient _httpClient;private readonly ILogger<HttpHelper>? _logger;public static string WebServiceUrl="";//WebServiceUrl=http://localhost:6666/api/Data/// 支持依赖注入的构造函数public HttpHelper(HttpClient httpClient, ILogger<HttpHelper>? logger = null){_httpClient = httpClient;_logger = logger;_httpClient.Timeout = TimeSpan.FromSeconds(30);}// 同步GET请求public HttpResponseEntity Get(string url, string traceId = ""){return GetAsync(url, traceId).GetAwaiter().GetResult();}// 异步GET请求public async Task<HttpResponseEntity> GetAsync(string url, string traceId = ""){try{using var response = await _httpClient.GetAsync(url);var content = await response.Content.ReadAsStringAsync();_logger?.LogInformation("[{TraceId}] GET {Url} - Status:{StatusCode}",traceId, url, response.StatusCode);return new HttpResponseEntity{IsSuccess = response.IsSuccessStatusCode,StatusCode = response.StatusCode,Content = content,TraceId = traceId};}catch (Exception ex){_logger?.LogError(ex, "[{TraceId}] GET {Url} failed", traceId, url);return new HttpResponseEntity{IsSuccess = false,ErrorMessage = ex.Message,TraceId = traceId};}}// 同步POST请求(支持JSON)public HttpResponseEntity Post(string url, string data, string traceId = ""){string NowUrl= WebServiceUrl+ url;return PostAsync(NowUrl, data, traceId).GetAwaiter().GetResult();}// 异步POST请求public async Task<HttpResponseEntity> PostAsync(string url, string data, string traceId = ""){try{var content = new StringContent(_data, Encoding.UTF8, "application/json");using var response = await _httpClient.PostAsync(url, content);var responseContent = await response.Content.ReadAsStringAsync();_logger?.LogInformation("[{TraceId}] POST {Url} - Status:{StatusCode}",traceId, url, response.StatusCode);return new HttpResponseEntity{IsSuccess = response.IsSuccessStatusCode,StatusCode = response.StatusCode,Content = responseContent,TraceId = traceId};}catch (Exception ex){_logger?.LogError(ex, "[{TraceId}] POST {Url} failed", traceId, url);return new HttpResponseEntity{IsSuccess = false,ErrorMessage = ex.Message,TraceId = traceId};}}
}public class HttpResponseEntity
{public bool IsSuccess { get; set; }public HttpStatusCode StatusCode { get; set; }public string? Content { get; set; }public string? ErrorMessage { get; set; }public string? TraceId { get; set; }
}
调用读取示例
//传输model
public class DataReq{public string Data { get; set; }public string DBstr { get; set; }}public class object1{public string str { get; set; }}
//请求
public void testpost(){DataReq r = new DataReq();r.Data = "[{\"str\":\"321\"},{\"str\":\"\"}]";r.DBstr = "123";//"{\"DBstr\":\"321\",\"Data\":\"\"}"string postData= JsonHelper.Serialize(r);string method = "GetTest";// 注册服务(控制台程序需手动创建)var services = new ServiceCollection();services.AddHttpClient<HttpHelper>();var provider = services.BuildServiceProvider();// 获取实例var httpHelper = provider.GetRequiredService<HttpHelper>();// 发送POST请求var postResponse = httpHelper.Post(method , postData, "TRACE456");if (postResponse.IsSuccess)return Ok("true");elsereturn Ok("false");
}//webapi接受请求[Route("api/[controller]/[action]")][ApiController]public class DataController : ControllerBase{[HttpPost]public async Task<IActionResult> GetTest(DataReq obj){List<object1> LIST = new List<object1>();if (!String.IsNullOrEmpty(obj.Data))LIST = JsonHelper.ToObj<List<object1>>(obj.Data);//解析数据string DBstr=obj.DBstr;//省略逻辑DataTable dt = ;//查询if (dt.Rows.Count == 0) return Ok("no");string JsonStr = JsonHelper.ToStr(dt);return Ok(JsonStr);}}
3、JsonHelper.cs Framework4.81
使用自带System.Runtime.Serialization.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
namespace ClassLibrary
{public static class JsonHelper{/// <summary>/// object =>JSON/// </summary>public static string Serialize<T>(T obj){DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));using (MemoryStream stream = new MemoryStream()){serializer.WriteObject(stream, obj);return Encoding.UTF8.GetString(stream.ToArray());}}/// <summary>/// JSON=> object/// </summary>public static T Deserialize<T>(string jsonString){DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString))){return (T)serializer.ReadObject(stream);}}/// <summary>/// List<object> =>JSON /// </summary>public static string SerializeToJson(List<object> list){var serializer = new DataContractJsonSerializer(list.GetType());using (var memoryStream = new MemoryStream()){serializer.WriteObject(memoryStream, list);memoryStream.Position = 0;using (var streamReader = new StreamReader(memoryStream)){return streamReader.ReadToEnd();}}}/// <summary>/// JSON=> List<object>/// </summary>public static List<T> DeserializeFromJson<T>(string jsonString) where T : class{var serializer = new DataContractJsonSerializer(typeof(List<T>));using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString))){return (List<T>)serializer.ReadObject(memoryStream);}}}
}
4、JsonHelper.cs NET8
nuget Newtonsoft.Json 包
using Newtonsoft.Json;
using System.IO;
namespace ClassLibrary
{public static class JsonHelper{// 将对象序列化为JSON字符串public static string ToStr(object obj){return JsonConvert.SerializeObject(obj);}// 将JSON字符串反序列化为指定类型的对象public static T ToObj<T>(string json){return JsonConvert.DeserializeObject<T>(json);}// 将对象序列化到文件public static void SerializeToFile(string filePath, object obj){string json = ToStr(obj);File.WriteAllText(filePath, json);}// 从文件读取JSON并反序列化为指定类型的对象public static T DeserializeFromFile<T>(string filePath){string json = File.ReadAllText(filePath);return ToObj<T>(json);}}
}
5、uniapp request.js 访问WEBAPI
VUE2/3 通用
/*request重写
调用示例
let obj={};
obj.Data = "[{\"str\":\"321\"},{\"str\":\"\"}]";
obj.DBstr = "123";
const params = {"object": "Data",//指向DataController "method": "GetTest",//指向方法"data": JSON.stringify(obj),}this.$request({data: params}).then((res) => {if (res.data == false) {} else {}}, err => {this.$mHelper.toast('请求失败');})}*/
import indexConfig from '@/common/config.js';
import assist from '@/common/assist.js';
const PATH = indexConfig.dataUrl;
//PATH= http://localhost:6666/api/
const request = (options) => {let url=PATH+'/'+options.data.object+'/'+options.data.methodoptions=options.data;uni.showLoading({title: '加载中'});options.url=url;options.method= 'POST';options.header = {'content-type': 'application/json','authorization':'Bearer '+assist.gdata("Token")}return new Promise((resolve,reject) => {console.log(JSON.stringify(options));uni.request({...options,success: (res) => {console.log(res);console.log(res.statusCode);if(res.statusCode == '403') {// 登录过期跳转到登录界面uni.showToast({title: '超时,请稍后再试!',icon: 'none'});// logOut()}if(res.statusCode == '-1') {uni.showToast({title: res.data.msg ? res.data.msg : '接口请求失败!',icon: 'none'});}uni.hideLoading();resolve(res);},fail: (err) => {console.log(err);console.log(options);uni.hideLoading();reject(err)},})})
}
export default request
缓存 assist.js
/*缓存写入*/
const expire=3600//1小时
function setCache(key, value, expire) {let obj = {data: value,time: Date.now()/1000,expire: expire}uni.setStorageSync(key, JSON.stringify(obj));
}
/*缓存读取*/
function getCache(key, value, expire) {let val = uni.getStorageSync(key);if (!val) return null;let obj = JSON.parse(val);if (Date.now() / 1000 - obj.time > obj.expire)//过期{uni.removeStorageSync(key);return null;}return obj.data;
}
export default {sdata:setCache,gdata:getCache,
}
main.js 全局申明
vue3
import $assist from '@/common/assist.js';//辅助函数
import $request from '@/common/request.js';//POST 重构
export function createApp() {const app = createSSRApp(App)app.use(store)//自定义配置 调用app.config.globalProperties.$assist = $assist;app.config.globalProperties.$request = $request;//-endreturn {app}
}
/*vue2 申明方法import Vue from 'vue'
//自定义
Vue.prototype.$assist= $assist;
Vue.prototype.$request = $request;
*/