首页
/ UnityHTTP 使用与技术文档

UnityHTTP 使用与技术文档

2024-12-28 14:18:08作者:齐冠琰

1. 安装指南

UnityHTTP 是基于 Simon Wittber 的 UnityWeb 代码的一个 HTTP 库,适用于 Unity 的 TcpClient。在开始使用之前,请确保您了解并接受该项目的 GPL 许可。

  • 确认 Unity 版本与 UnityHTTP 兼容。
  • 下载 UnityHTTP 库文件。
  • 将下载的文件导入到您的 Unity 项目中。

2. 项目的使用说明

UnityHTTP 支持在 Unity 的独立播放器和网络播放器中使用。该项目提供了与 JSON 数据交互的便捷方法。

基础用法

使用协程(Coroutine)进行 HTTP 请求:

public IEnumerator SomeRoutine() {
    HTTP.Request someRequest = new HTTP.Request( "get", "http://someurl.com/somewhere" );
    someRequest.Send();

    while( !someRequest.isDone )
    {
        yield return null;
    }

    JSONObject thing = new JSONObject( someRequest.response.Text );
}

使用闭包(Closure)进行 HTTP 请求(不需要在协程中):

HTTP.Request someRequest = new HTTP.Request( "get", "http://someurl.com/somewhere" );
someRequest.Send( ( request ) => {
    JSONObject thing = new JSONObject( request.response.Text );
});

表单数据 POST 请求

WWWForm form = new WWWForm();
form.AddField( "something", "yo" );
form.AddField( "otherthing", "hey" );

HTTP.Request someRequest = new HTTP.Request( "post", "http://someurl.com/some/post/handler", form );
someRequest.Send( ( request ) => {
    bool result = false;
    Hashtable thing = (Hashtable)JSON.JsonDecode( request.response.Text, ref result );
    if ( !result )
    {
        Debug.LogWarning( "JSON 解析失败!" );
        return;
    }
});

JSON 数据 POST 请求

Hashtable data = new Hashtable();
data.Add( "something", "hey!" );
data.Add( "otherthing", "YO!!!!" );

HTTP.Request theRequest = new HTTP.Request( "post", "http://someurl.com/a/json/post/handler", data );
theRequest.Send( ( request ) => {
    Hashtable result = request.response.Object;
    if ( result == null )
    {
        Debug.LogWarning( "JSON 解析失败!" );
        return;
    }
});

非播放模式下的请求

在非播放模式下(例如自定义编辑器菜单命令或向导),您必须同步使用请求,因为 Unity 的主更新循环没有运行。调用将阻塞,直到响应可用。

Hashtable data = new Hashtable();
data.Add( "something", "hey!" );
data.Add( "otherthing", "YO!!!!" );

HTTP.Request theRequest = new HTTP.Request("post", "http://someurl.com/a/json/post/handler", data );
theRequest.synchronous = true;
theRequest.Send((request) => {
    EditorUtility.DisplayDialog("请求已发送。", request.response.Text, "确定");
});

3. 项目 API 使用文档

UnityHTTP 提供了以下类和方法供您使用:

  • HTTP.Request: 构造和发送 HTTP 请求。

    • Send(): 发送请求。
    • Send(Action<HTTP.Request> callback): 发送请求,并提供完成后的回调函数。
    • isDone: 检查请求是否完成。
    • response: 获取响应数据。
    • synchronous: 设置请求是否为同步。
  • JSONObject: 解析 JSON 字符串。

  • WWWForm: 构建 POST 请求的表单数据。

4. 项目安装方式

请遵循以下步骤安装 UnityHTTP:

  1. 确认您的 Unity 项目与 UnityHTTP 兼容。
  2. 下载 UnityHTTP 库文件。
  3. 将下载的文件导入到您的 Unity 项目中。
  4. 开始使用 UnityHTTP 进行 HTTP 请求。
登录后查看全文
热门项目推荐