unity get post 請求,node服務器

安裝node,配置環境

npm install express

服務器代碼   webserver.js

var express = require("express")
var app = express()
var path = require("path")
//靜態網頁目錄,process.cwd()爲當前目錄
app.use(express.static(path.join(process.cwd(),"www_root")))
//服務器端口
app.listen("6080");
 
// 設置我們的跨域訪問
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});
// end
 
//添加一個get請求接口,如果需要別的接口,修改login,或者在添加一個就可以了
app.get("/Login",function(request,response){
    //打印客戶端傳來的數據,這裏的數據是從url後面傳進來的
    console.log(request.query);
    response.send("SUCCESS");
});
 
//添加一個post接口
app.post("/upload",function (request,response) {
    //打印客戶端傳來的數據,這裏的數據是從url後面傳進來的
    console.log(request.query);
    request.on("data",function(data){
        //客戶端body裏傳過來的數據
        console.log(data.toString());
        //傳給客戶端的數據
        var testData = {
            "數據1":1,
            "數據2":222,
        };
        //傳一個數據給客戶端
        response.send(JSON.stringify(testData));
    });
})

console.log("app啓動")

客戶端代碼

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public enum ReqType {
   www_get=1,
   web_get=2,
   www_post=3,
   web_post=4,
}

public class WebRequst : MonoBehaviour {

    int idx = 0;

	
	// Update is called once per frame
	void Update () {
        if (Input.GetKeyDown(KeyCode.Space)) {
            idx++;
            if (idx > 4) {
                idx = 1;
            }
            Req();
        }
	}

    private void Req() {
        switch ((ReqType)idx)
        {
            case ReqType.www_get: { StartCoroutine(GetSys()); } break;
            case ReqType.web_get: { StartCoroutine(TestWeb()); } break;
            case ReqType.www_post: { StartCoroutine(PostSys()); } break;
            case ReqType.web_post: { StartCoroutine(TestWebPost()); } break;
        }
    }

    IEnumerator GetSys()
    {
        //服務器地址
        string url = "http://127.0.0.1:6080/";
        //get請求的接口
        string getInterface = "Login";
        //傳給服務器的數據,?開頭,每條數據以key=value的形式用&拼接起來
        string getParams = "?uname=dx&pwd=123456";
        WWW _www = new WWW(url + getInterface + getParams);
        yield return _www;
        if (_www.isDone && string.IsNullOrEmpty(_www.error))
        {
            //服務器傳過來的數據
            Debug.Log(_www.text);
        }
        else
        {
            Debug.Log(_www.error);
        }
    }

    IEnumerator TestWeb()
    {
        //服務器地址
        string url = "http://127.0.0.1:6080/";
        //get請求的接口
        string getInterface = "Login";
        //傳給服務器的數據,?開頭,每條數據以key=value的形式用&拼接起來
        string getParams = "?uname=dx&pwd=123456";
        UnityWebRequest _UnityWebRequest = UnityWebRequest.Get(url + getInterface + getParams);
        yield return _UnityWebRequest.SendWebRequest();
        if (_UnityWebRequest.isHttpError || _UnityWebRequest.isNetworkError)
        {
            Debug.Log(_UnityWebRequest.error);
        }
        else
        {
            Debug.Log(_UnityWebRequest.downloadHandler.text);
        }
    }

    IEnumerator PostSys()
    {
        //服務器地址
        string url = "http://127.0.0.1:6080/";
        //get請求的接口
        string getInterface = "upload";
        //傳給服務器的數據,?開頭,每條數據以key=value的形式用&拼接起來
        string getParams = "?key=post測試&文件名=log.txt";

        WWWForm _WWWForm = new WWWForm();
        //傳給服務器的數據(就是body數據)
        _WWWForm.AddField("log", "測試");
        //unity封裝的另一種添加方法
        _WWWForm.AddBinaryData("log1", System.Text.Encoding.UTF8.GetBytes("測試2"));
        //unity裏默認添加了這個頭了,就不需要添加了
        //_WWWForm.headers.Add("Content-Type", "application/x-www-form-urlencoded");
        //_WWWForm.headers.Add("Content-Length", _WWWForm.data.Length.ToString());
        WWW _www = new WWW(url + getInterface + getParams, _WWWForm);

        yield return _www;
        if (_www.isDone && string.IsNullOrEmpty(_www.error))
        {
            Debug.Log(_www.text);
        }
        else
        {
            Debug.Log(_www.error);
        }
    }

    IEnumerator TestWebPost()
    {
        //服務器地址
        string url = "http://127.0.0.1:6080/";
        //get請求的接口
        string getInterface = "upload";
        //傳給服務器的數據,?開頭,每條數據以key=value的形式用&拼接起來
        string getParams = "?key=post測試&文件名=log.txt";

        WWWForm _WWWForm = new WWWForm();
        _WWWForm.AddField("log", "測試");
        _WWWForm.AddBinaryData("log1", System.Text.Encoding.UTF8.GetBytes("測試2"));
        UnityWebRequest _UnityWebRequest = UnityWebRequest.Post(url + getInterface + getParams, _WWWForm);
        yield return _UnityWebRequest.SendWebRequest();
        if (_UnityWebRequest.isHttpError || _UnityWebRequest.isNetworkError)
        {
            Debug.Log(_UnityWebRequest.error);
        }
        else
        {
            Debug.Log(_UnityWebRequest.downloadHandler.text);
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章