unity实现HTTP请求

unity中UnityWebRequest和WWW都可以实现HTTP请求,下面举例说明两种方法分别实现Get和Post请求

1、UnityWebRequest实现HTTP请求

Get请求

IEnumerator GetRequest(string url)
{
    using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
    {
        yield return webRequest.SendWebRequest();
        if (!string.IsNullOrEmpty(webRequest.error))
        {
            Debug.LogError(webRequest.error);
        }
        else
        {
            Debug.Log(webRequest.downloadHandler.text);
        }
    }
}

Post请求

IEnumerator PostRequest(string url)
{
    WWWForm form = new WWWForm();
    form.AddField("name", "posttest");
    using (UnityWebRequest webRequest = UnityWebRequest.Post(url, form))
    {
        yield return webRequest.SendWebRequest();
        if (!string.IsNullOrEmpty(webRequest.error))
        {
            Debug.LogError(webRequest.error);
        }
        else
        {
            Debug.Log(webRequest.downloadHandler.text);
        }
    }
}

Post请求需要用到WWWForm来添加post数据,WWWForm.AddBinaryData还可以添加二进制数据(如上传文件)。

2、WWW实现HTTP请求

Get请求

IEnumerator GetRequest(string url)
{
    using (WWW www = new WWW(url))
    {
        yield return www;
        if (!string.IsNullOrEmpty(www.error))
        {
            Debug.LogError(www.error);
        }
        else
        {
            Debug.Log(www.text);
        }
    }
}

Post请求

IEnumerator PostRequest(string url)
{
    WWWForm form = new WWWForm();
    form.AddField("name", "posttest");
    using (WWW www = new WWW(url, form))
    {
        yield return www;
        if (!string.IsNullOrEmpty(www.error))
        {
            Debug.LogError(www.error);
        }
        else
        {
            Debug.Log(www.text);
        }
    }
}

为了验证上述请求,用Node搭建一个简单的服务器

Get请求测试服务器

var http = require("http");
var url=require('url');

http.createServer(function(req, res){
    // 解析 url 参数,返回给客户端
    var params = url.parse(req.url, true).query;
    res.write("name:" + params.name);
    res.end();
 
}).listen(8888);

运行服务器后,在客户端调用下列代码即可

string getUrl = "http://127.0.0.1:8888?name=gettest";
StartCoroutine(GetRequest(getUrl));

Post请求测试服务器

var http = require("http");
var querystring = require('querystring');
var util=require('util');
http.createServer(function(request, response) {  
    var post = '';
    request.on('data', function(chunk){    
        post += chunk;
    });
	request.on('end', function(){    
		post = querystring.parse(post);
        response.end(util.inspect(post));		
    });
}).listen(8889);

客户端运行下列代码

string postUrl = "http://127.0.0.1:8889";
StartCoroutine(PostRequest(postUrl));

一切顺利的话会打印如下消息

unity实现HTTP请求_第1张图片

你可能感兴趣的:(Unity3D)