您的位置:首页 > 理论基础 > 计算机网络

Unity的http通信--unity与python的django通信

2013-12-18 17:41 393 查看
写在前面:

WWW类,是unity里,简单的访问网页的类。本文介绍的就是这种方式,与web服务器之间进行通信。当然,HTTP通信,也可以自己通过socket去写,自己实现一个http通信。

WWW类可以用来发送GET和POST请求到服务器,WWW类默认使用GET方法,并且如果提供一个postData参数可用POST方法。这里我们主要使用实用性更强一些的POST方式。

WWW的完整构造函数如下:

WWW( url:string, postData:byte[], headers:Hashtable )

url
The url to download.

postData
A byte array of data to be posted to the url.

headers
A hash table of custom headers to send with the request.

■注意:这个构造函数,有函数重载,可以省略第三个headers参数,也就是:

WWW( url:string, postData:byte[] )

实际例子:

1,新建一个空项目。【File】-->【New Project】
2,新建一个2D背景,用于衬托UI。【GameObject】-->【CreateOther】-->【GUI Texture】

3,写HttpTest.cs脚本文件,绑定到摄像机上。代码如下:

using UnityEngine;
using System.Collections;

public class HttpTest : MonoBehaviour {
//variables
public string str_uid = "";
public string str_score = "";
public string str_response = "";

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

}

//在C#中, 需要用到yield的话, 必须建立在IEnumerator类中执行
IEnumerator TestPost()
{
//WWW的三个参数: url, postData, headers
string url = "http://127.0.0.1/test/";
byte[] post_data;
Hashtable headers;   //System.Collections.Hashtable

string str_params;
str_params = "uid=" + str_uid + "&" + "score=" + str_score;
post_data = System.Text.UTF8Encoding.UTF8.GetBytes(str_params);
//Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
//byte[] post_data = encode.GetBytes("uid=中文&score=100");
headers = new Hashtable();
//headers.Add("Content-Type","application/x-www-form-urlencoded");
headers.Add("CONTENT_TYPE", "text/plain");

//发送请求
WWW www_instance = new WWW(url, post_data, headers);

//web服务器返回
yield return www_instance;
if (www_instance.error != null)
{
Debug.Log(www_instance.error);
}
else
{
this.str_response = www_instance.text;
}
}

void OnGUI () {
GUI.Label(new Rect(10,20,60,20),"UID:   ");
GUI.Label(new Rect(10,45,60,20),"Score: ");
//注意:因为每一帧都在刷, 所以[文本框]是这种写法:
str_uid = GUI.TextField(new Rect(60, 20, 160, 20), str_uid);
str_score = GUI.TextField(new Rect(60, 45, 160, 20), str_score);

//发送Http的POST请求
if (GUI.Button(new Rect(120,80,100,25),"发送请求"))
{
StartCoroutine(TestPost());
}

this.str_response = GUI.TextArea(new Rect(10, 150, 210, 100), this.str_response);
}
}


4,运行。效果如下:




5,点击,发送POST请求,并显示服务器返回的结果:



附注A:

下面是对应的web服务器端代码:

本例的web服务器,使用的是python的django,使用方法可以参加我上一篇文章:【新版django1.6的Hello world】

views代码如下:

#! /usr/bin/env python
#coding=utf-8

from django.http import HttpResponse

def test_post(request):
fanhui = u'服务器返回:\n' + u'用户UI:'+ unicode(request.POST['uid']) +'\n'
fanhui = fanhui + u'分数:'+ unicode(request.POST['score'])
return HttpResponse(fanhui)


附注B:

如果使用django,注意要把中间件里的:

'django.middleware.csrf.CsrfViewMiddleware', 注释掉。否则请求会因为CSRF机制,给拦下,报403错误。

或者干脆禁用中间件,也行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: