Unity接图灵机器人

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;
using System.Text;
using UnityEngine.UI;

public class TuLingTest : MonoBehaviour
{
    private string url = "http://openapi.tuling123.com/openapi/api/v2";
    private string apiKey = "1890a0125030444d8c4a2779f813e41e";
    public InputField InputText;
    public InputField id;
    public Text text;

    private void Update()
    {
        if(Input.GetKeyDown(KeyCode.A))                                   //按A发送消息,(鼠标要移出输入框)
        {
            HttpPostFunc(InputText.text);
        }
    }

    public void HttpPostFunc(string message)
    {
        StartCoroutine(HttpPost(message));
    }

    IEnumerator HttpPost(string message)
    {
        //JsonData可以表示JsonObject{},也可以表示JsonArry[]//4e03ee9c4e8cc2af//"1512267543"
        JsonData request = new JsonData();
        //perception
        request["perception"] = new JsonData();
        request["perception"]["inputText"] = new JsonData();
        request["perception"]["inputText"]["text"] = message;
        //userInfo
        request["userInfo"] = new JsonData();
        request["userInfo"]["apiKey"] = apiKey;
        request["userInfo"]["userId"] = id.text;
        //JsonMapper.ToJson(request)
        //将Json对象转为Json字符串,直接ToString容易出错
        //将Json字符串转为字节数组
        //进行一个网络推送
        WWW post = new WWW(url, Encoding.UTF8.GetBytes(JsonMapper.ToJson(request)));
        yield return post;
        Debug.Log(post.text);
        JsonData response = JsonMapper.ToObject(post.text);
        string result = response["results"][0]["values"]["text"].ToString();
        Debug.Log(result);
        text.text += "我:" + message + "\n" + "机器人:" + result + "\n";
    }
}

Unity接图灵机器人_第1张图片

你可能感兴趣的:(Unity)