前言
参考文章:
用C#进行MES系统的对接,同时要发送JSON请求。最后要从MES系统中获得相应的应答。
我期望的是能够用一个类将HTTP请求和响应处理进行封装。
一、引入命名空间
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
二、ApiClient类进行封装
public class ApiClient
{
private readonly string apiUrl;
private readonly HttpClient client;
public ApiClient(string apiUrl)
{
this.apiUrl = apiUrl;
this.client = new HttpClient();
this.client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
}
public YourResponseModel SendRequest(object requestBody)
{
try
{
var jsonContent = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync(apiUrl, jsonContent).Result;
if (response.IsSuccessStatusCode)
{
string responseContent = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<YourResponseModel>(responseContent);
}
else
{
Console.WriteLine($"请求失败,状态码: {
response.StatusCode}");
return null; // 或者抛出异常,取决于您的需求
}
}
catch (Exception ex)
{
Console.WriteLine($"发生错误: {
ex.Message}");
throw; // 重新抛出异常,以便调用者知道发生了错误
}
}
}
三、定义响应模型类
public class YourResponseModel
{
public string resultCode {
get; set; }
public string resultMsg {
get; set; }
public ResultData resultData {
get; set; }
}
public class ResultData
{
public int pageNo {
get; set; }
public int totalPage {
get; set; }
public int totalSize {
get; set; }
public object[] data {
get; set; }
public int pageSize {
get; set; }
}
四、发送请求并处理请求
class Program
{
static void Main(string[] args)
{
string apiUrl = "http://10.0.0.0:8888/api";
var apiClient = new ApiClient(apiUrl);
var requestBody = new
{
docType = "MES***LB**PROCESS",
updateType = "UPDATE",
data = new[]
{
new
{
mo_code = "001102982621-210",
vehicles_code = "FL12",
mes_mo_lbwp_qc = new[]
{
new
{
ng_item_code = (string)null
}
},
prod_stat = "1",
lb_id = "S5J5.24A**1603789",
wu_code = "20T_P40_ST08",
s_date = "2024-10-17T09:58:36.3847994+08:00",
acupoint = "10",
wp_code = "**XNY0**10"
}
}
};
// 使用 Task 来启动一个新的线程执行 HTTP 请求
Task.Run(() =>
{
try
{
YourResponseModel response = apiClient.SendRequest(requestBody);
if (response != null)
{
Console.WriteLine($"Response received: {
response.resultCode} - {
response.resultMsg}");
}
}
catch (Exception ex)
{
Console.WriteLine($"发生错误: {
ex.Message}");
}
}).Wait(); // 等待任务完成,如果不需要等待,可以去掉 .Wait()
}
}
更新时间
- 2024.10.28:创建