Unity使用WWW类调用Restful接口

本文介绍了如何在Unity中使用WWW类进行RESTful API的调用,包括简单的GET和POST请求,带安全验证的请求,以及如何封装成带回调函数的请求方式,提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 BEGIN

维基百科,自由的百科全书

具象状态传输(英文:Representational State Transfer,简称REST)是Roy Thomas Fielding博士于2000年在他的博士论文 “Architectural Styles and the Design of Network-based Software Architectures” 中提出来的一种万维网软件架构风格。
目前在三种主流的Web服务实现方案中,因为REST模式与复杂的SOAP和XML-RPC相比更加简洁,越来越多的web服务开始采用REST风格设计和实现。例如,Amazon.com提供接近REST风格的Web服务执行图书查询;雅虎提供的Web服务也是REST风格的。

RESTful API是目前比较成熟的一套互联网应用程序的API设计理论。

2 简单的Get请求

基本http的GET请求需要在一个协程中new一个WWW类并传入准确的API地址,执行yield return www 就会等待服务器的返回结果,之后才开始执行以后的代码。 Get请求的API参数需要加入到API的地址中去,格式 URL+?key1=value1&key2=value2

public class NewBehaviourScript : MonoBehaviour {

    // Use this for initialization
    void Start () {
        StartCoroutine (IEHttpGet());

    }

    IEnumerator IEHttpGet()
    {
        //print ("get url " + fullUrl);
        WWW www = new WWW("http://127.0.0.1:6789/bmi");
        yield return www;

        if (www.error != null) {
            Debug.LogError (www.error);
        } 

        Debug.Log (www.text);
    }
}

3 简单的Post请求

这份代码使用的是JSON格式的数据。POST请求需要一个API地址,请求的HTTP头部需要加入头信息表明是json格式的数据,发送的josn数据格式化为字符串并转化为字节数据。这里使用的JSON解析库是MiniJSON。

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using MiniJSON;

public class NewBehaviourScript : MonoBehaviour {

    // Use this for initialization
    void Start () {
        StartCoroutine (IEPost());

    }

    IEnumerator IEPost()
    {
        string fullUrl = "http://127.0.0.1:6789/bmi";

        //加入http 头信息
        Dictionary<string,string> JsonDic = new Dictionary<string,string> ();  
        JsonDic.Add ("Content-Type", "application/json");

        //请求的Json数据
        Dictionary<string,string> UserDic = new Dictionary<string, string> ();
        UserDic ["height"] = "170";
        UserDic ["weight"] = "62";
        string data = Json.Serialize (UserDic);

        //转换为字节
        byte[] post_data;  
        post_data = System.Text.UTF8Encoding.UTF8.GetBytes (data);  

        WWW www = new WWW (fullUrl, post_data, JsonDic);
        yield return www;

        if (www.error != null) {
            Debug.LogError ("error:" + www.error);
        } 
        Debug.Log (www.text);
    }
}

4 带安全验证的Get/Post请求

对于需要使用Base Auth 安全验证的RESTful API,需要在http的请求信息中加入用户名称和用户帐号信息,并进行编码转化。

新建一个字典数据,加入编码说明和帐号信息。

Dictionary<string,string> AuthDic = new Dictionary<string,string> ();  // auth header
AuthDic.Add("Content-Type", "application/json");
string NameAndPw = "UserName" + ":" + "Password";
AuthDic.Add("Authorization", "Basic " + System.Convert.ToBase64String(System.Text.Encoding
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值