C# 请求第三方接口方式

方式1

curl

string postData = JsonConvert.SerializeObject(requestData);

// 定义curl命令及其参数

string curlPath = "curl"; // 假设curl命令在系统的PATH环境变量中

string path = "-X POST -H "Content-Type: application/json;charset=UTF-8" -H "Accept-Charset: UTF-8" -H "Accept-Encoding: gzip, deflate" -H "Accept-Language: zh-CN,zh;q=0.9" -d " + Regex.Replace(postData, @"""|\", "\$&") + " " + GlobalInfo.BaseUrl + "/weightCheck/submitSpc"; // curl的参数,即你想要执行的HTTP请求

// 创建ProcessStartInfo对象来配置进程启动信息

ProcessStartInfo startInfo = new ProcessStartInfo

{

FileName = curlPath, // 命令行程序的名称或路径

Arguments = path, // 传递给命令行程序的参数

UseShellExecute = false, // 是否使用操作系统shell启动进程

RedirectStandardOutput = true, // 是否将输出重定向到Process.StandardOutput流

CreateNoWindow = true // 不创建新窗口

};

string output;

// 启动进程并执行命令

using (Process process = new Process { StartInfo = startInfo })

{

process.Start();

复制代码
// 使用 UTF-8 编码的 StreamReader 异步读取进程的标准输出  
using (StreamReader reader = new StreamReader(process.StandardOutput.BaseStream, Encoding.UTF8))
{
    output = await reader.ReadToEndAsync(); // 异步读取所有输出
    Console.WriteLine(output); // 打印输出到控制台  
}

await process.WaitForExitAsync(); // 异步等待进程完成
process.Close();

}

var json = JsonConvert.DeserializeObject(output);

if (json.code.Equals(20000) && json.data != null)

{

Growl.Success(new GrowlInfo() { Message = "提交成功!", WaitTime = 1 });

return JsonConvert.DeserializeObject<List>(json.data.ToString());

}

else

{

throw new Exception($"请确认网络连接是否正常!! - 错误码: {json.code}");

}

方式2

HttpClient

using (var httpClient = new HttpClient())

{

httpClient.Timeout = TimeSpan.FromSeconds(20);

复制代码
 var content = new StringContent(postData, Encoding.UTF8, "application/json");

 using (var response = await httpClient.PostAsync(GlobalInfo.BaseUrl + "/weightCheck/submitSpc", content))
 {
     if (response.IsSuccessStatusCode)
     {
         string responseBody = await response.Content.ReadAsStringAsync();
         var json = JsonConvert.DeserializeObject<ResponseDto>(responseBody);

         if (json.code == 20000 && json.data != null)
         {
             XTrace.WriteLine($"提交成功!");
             return JsonConvert.DeserializeObject<List<SpcLimitDto>>(json.data.ToString());
         }
     }
     else
     {
         // Handle unsuccessful response
         Console.WriteLine($"HTTP request failed with status code {response.StatusCode}");
     }
 }

}

方式3

RestSharp

try

{

var client = new RestClient(GlobalInfo.BaseUrl);

var request = new RestRequest("/weightCheck/submitSpc", Method.Post);

request.AddHeader("Content-Type", "application/json");

request.AddHeader("Accept", "application/json");

request.AddParameter("application/json", postData, ParameterType.RequestBody);

复制代码
 RestResponse response = client.Execute(request);
 var content = response.Content;

 if (response.StatusCode == HttpStatusCode.OK)
 {
     var json = JsonConvert.DeserializeObject<ResponseDto>(content);

     if (json.code.Equals(20000) && json.data != null)
     {
         Growl.Success(new GrowlInfo() { Message = "提交成功!", WaitTime = 1 });
         spcDataList = JsonConvert.DeserializeObject<List<SpcLimitDto>>(json.data.ToString());
         return spcDataList;
     }
     else
     {
         throw new Exception($"请确认网络连接是否正常!! - 错误码: {json.code}");
     }
 }
 else
 {
     throw new Exception($"请求失败: {response.StatusCode}");
 }

}

catch (Exception ex)

{

Growl.Error(new GrowlInfo() { Message = $"提交失败! -{ex.Message}", WaitTime = 2 });

throw; // 抛出异常以供调用者处理

}

相关推荐
奇树谦3 分钟前
LRU 缓存原理与 C++ 实践示例
开发语言·c++·缓存
toooooop85 分钟前
FastAdmin Hook 机制与插件错误透传:`$result` 之外的信封
开发语言·fastadmin
小马过河R29 分钟前
EdgeOne深度解析:从原理、适用场景到COS接入的技术逻辑
java·开发语言·前端·spring·cos
多弗朗皮卡丘37 分钟前
C++ 红黑树
开发语言·c++·红黑树
ZoeLandia1 小时前
TypeScript 04:类型断言与类型守卫
开发语言·前端·typescript
geovindu1 小时前
rust: pool Pattern
开发语言·后端·设计模式·rust·对象池简写模式
jimy11 小时前
标准的动态类型定义与“多态”无关,非多态对象同样会出现动态类型不同于静态类型的情形
开发语言·c++
冬、不眠的夜1 小时前
Nuitka 将 python 程序编译成 exe 指南
开发语言·python
CVer儿1 小时前
起源1引擎相关知识点2--World Brush+func_detail
开发语言
薛之谦_2 小时前
JAVA 多线程编程:从基础原理到实战应用
java·开发语言