最近需要在unity中使用http post的方式传递消息,所以做一下记录吧
1、unity自己的www 方式
因为我传递的消息是json字符串所以前期的工作就是 拼字符串然后通过litjson或者newtonsoft.json等库转换成byte数组然后,,,,,直接上代码吧
IEnumerator SendToTuring()
{
JsonMsg jsMsg = new JsonMsg();
jsMsg.reqType = 0;
jsMsg.perception = new Perception();
jsMsg.perception.inputText = new InputText();
jsMsg.userInfo = new UserInfo();
jsMsg.perception.inputText.text = "你好";
jsMsg.userInfo.apiKey = "8bcdd2feb55143b4adc958fed9c9f536";
jsMsg.userInfo.userId = "284239";
string input = JsonMapper.ToJson(jsMsg);
byte[] byteArry = System.Text.Encoding.UTF8.GetBytes(input);
WWW getData = new WWW(url, byteArry);
yield return getData;
if(getData.error != null)
{
Debug.Log(getData.error);
}
else
{
Debug.Log(getData.text);
}
}
2、主动post的方法(这个貌似是纯C#的方法)
也是直接上代码
string PostStr2Unit(string recStr)
{
string token = "24.f50db32087fd2**********.1546683946.282335-15076515";
string url = "https://aip.baidubce.com/rpc/2.0/unit/bot/chat?access_token=";
//logid++;
string logId = "Sd" + System.DateTime.Now;
string str = "{"bot_session":"",";
str += ""log_id":"785426",";
str += ""request":";
str += "{"bernard_level":1,";
str += ""client_session":";
str += ""{\\"client_results\\":\\"\\", ";
str += "\\"candidate_options\\":[]}",";
str += ""query":"" + recStr + "",";
str += ""query_info":{"asr_candidates":[],"source":"KEYBOARD","type":"TEXT"},"updates":"","user_id":"88888"},"bot_id":"15554","version":"2.0"}";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + token);
request.Method = "post";
request.ContentType = "application/json";
request.KeepAlive = true;
Debug.Log(str);
byte[] byteArry = Encoding.UTF8.GetBytes(str);
request.ContentLength = byteArry.Length;
request.GetRequestStream().Write(byteArry, 0, byteArry.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string result = reader.ReadToEnd();
JObject jdata = (JObject)JsonConvert.DeserializeObject(result);
Debug.Log(jdata);
string intent = jdata["result"]["response"]["schema"]["intent"].ToString();
return intent;
}
对比发现貌似是www的方法必须得放到协程里面才能使用,但是直接post的方法不用,根据不同场景调用不同的函数吧,也不能说谁优谁劣,毕竟使用合适的函数才是优秀的代码对吧
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)