You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python Requests API调用转为Unity中的C#实现?

问题:Python Requests POST请求转Unity C#实现问题

我正尝试将一段Python中的Requests API调用代码转换为C#代码,以便集成到我开发的Unity应用中。

原Python代码

response = requests.request(
    method=method,
    url=url.as_uri(),
    verify=settings.CACERT_FILE,
    **kwargs,
)

已知参数

  • method为POST
  • verify为None
  • kwargs为{'json': {'time': 1, 'types': ['the_types']}}

我的C#尝试代码

初始版本

var client = new HttpClient();
client.BaseAddress = new Uri("theurl.com");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = client.GetAsync("{'json': {'time': 1, 'types': ['the_types']}}").Result;  
if (response.IsSuccessStatusCode)
{
    Debug.Log("Worked");
}
else
{
    Debug.Log("Didn't work");
}
client.Dispose();

编辑后版本(改用PostAsync)

HttpResponseMessage response = client.PostAsync(new Uri("theUrl"), new StringContent("{'json': {'time': 1, 'types': ['the_types']}}")).GetAwaiter().GetResult();

我刚接触C#,不清楚自己哪里出错了,也不知道后续该如何调整。提前感谢帮助!


问题分析与修正方案

核心错误点

  • 请求方法错误:原Python请求是POST,但初始代码用了GetAsync,后来改成PostAsync是正确方向,但仍有其他问题。
  • 请求体格式错误:直接传入Python风格的字典字符串无效,C#需要将对象序列化为标准JSON格式,并指定正确的媒体类型。
  • 同步调用阻塞主线程:Unity中直接用.Result或GetAwaiter().GetResult()会阻塞主线程,可能导致卡顿,应使用异步await。
  • SSL验证未处理:原Python中verify=None对应跳过SSL证书验证,C#需要额外配置HttpClientHandler。
  • URL处理不当:设置BaseAddress后,PostAsync只需传相对路径,无需重复传入完整Uri。

修正后的完整代码

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json; // 需要通过Unity Package Manager安装Newtonsoft.Json包
using UnityEngine;

public class ApiRequestExample : MonoBehaviour
{
    // 定义请求体模型类,方便JSON序列化
    private class RequestBody
    {
        public int time { get; set; }
        public List<string> types { get; set; }
    }

    // 调用此方法发送POST请求
    public async void SendPostRequest()
    {
        // 配置HttpClientHandler,跳过SSL验证(对应Python的verify=None)
        var handler = new HttpClientHandler();
        handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;

        // 使用using自动释放资源
        using (var client = new HttpClient(handler))
        {
            client.BaseAddress = new Uri("https://theurl.com/"); // 注意URL末尾添加斜杠
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // 构造请求体数据
            var requestData = new RequestBody
            {
                time = 1,
                types = new List<string> { "the_types" }
            };

            // 将对象序列化为标准JSON字符串
            string jsonBody = JsonConvert.SerializeObject(requestData);
            // 创建请求内容,指定编码和媒体类型为application/json
            var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

            try
            {
                // 异步发送POST请求,避免阻塞Unity主线程
                HttpResponseMessage response = await client.PostAsync("api/relative/path", content); // 替换为实际的相对路径

                if (response.IsSuccessStatusCode)
                {
                    Debug.Log("请求成功!");
                    // 读取响应内容(可选)
                    string responseContent = await response.Content.ReadAsStringAsync();
                    Debug.Log("响应内容:" + responseContent);
                }
                else
                {
                    Debug.Log($"请求失败,状态码:{response.StatusCode}");
                    // 读取错误详情(可选)
                    string errorDetails = await response.Content.ReadAsStringAsync();
                    Debug.Log("错误信息:" + errorDetails);
                }
            }
            catch (Exception ex)
            {
                Debug.Log($"请求发生异常:{ex.Message}");
            }
        }
    }
}

关键说明

  1. JSON序列化:推荐使用Newtonsoft.Json(Unity可通过Package Manager安装),比Unity自带的JsonUtility支持更复杂的类型和格式。
  2. 异步处理:使用async/await确保Unity主线程不被阻塞,避免游戏卡顿。
  3. HttpClient复用:如果需要频繁发送请求,建议将HttpClient设为全局单例,避免频繁创建销毁带来的性能损耗。
  4. SSL验证:仅在测试环境或信任的服务器下跳过验证,生产环境应导入合法的CA证书,确保通信安全。

内容的提问来源于stack exchange,提问作者Bob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 03:09:26