unity網絡編程學習(3)與javaWeb的http通信

前言

unity想要實現和網頁之間傳遞數據的功能,就要用到Unity中的WWW類,它是一個簡單的訪問網頁的類,用於檢索URL內容的小工具模塊。如果你想從web服務器上獲取一些數據,例如高分列表或者調用主頁,可以使用這個,也有一些功能可以使用從web上下載的圖片來創建一個紋理,或者下載或加載新的web播放器數據文件。WWW類可以用來發送GET和POST請求到服務器,WWW類默認使用GET方法,並且如果提供一個postData參數可用POST方法。

讓我們來看一下它的構造參數吧

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

Parameters參數

url The url to download. 請求的網址
postData A byte array of data to be posted to the url. 數據post到url的一個字節數組
headers A hash table of custom headers to send with the request. 第三個參數,可以省略

看看效果


請求得到了回覆,圖片也下載下來了,

實現

服務器的搭建,通過eclipse來創建一個web工程,創建過程就不演示了,創建一個helloworld,開啓服務器,看看是否正常運行
看來沒問題
之後我們需要創建一個servlet文件,來處理來自unity的請求和回覆內容
package com.zx.uinty;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet 
 */
@WebServlet("/Servlet")
public class Servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Servlet() {
        super();
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("doget");
		this.excute(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("dopost");
		this.excute(request, response);
	}
	
	private void excute(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {	
		//設置編碼格式
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		//獲取參數
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		System.out.println("id是: "+id+" name是: "+name);
		//設置文檔類型爲text
		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();
		out.println("服務器返回");
		out.println("訪問方式爲: "+request.getMethod()+"\n"+"得到的參數是:id "+id+", name "+name);
	}
	
	 public void destroy() {  
	    }  

}
將一張圖片放入到WebContent文件夾下,用來測試www類下載圖片的功能,這樣服務器端需要的內容就已經完成了,保證服務的開啓。
通過Ngui來搭建一個簡單的場景。
創建一個c#腳本,掛在MainCamera上作爲控制腳本 給按鈕添加方法,點擊時觸發
using UnityEngine;
using System.Collections;

public class test : MonoBehaviour {

    public UIInput id, name,text;
    public UITexture Pic;

    /*點擊提交按鈕,發送請求,傳遞參數*/
    public void OnSubmit()
    {
        Debug.Log("進入OnSubmit方法");
        StartCoroutine(TestPost());
    }
    /*點擊下載圖片按鈕,下載圖片*/
    public void OnDownPic()
    {
        StartCoroutine(TestDown());
    }
    //在C#中, 需要用到yield的話, 必須建立在IEnumerator類中執行  
    IEnumerator TestPost()
    {   
        //WWW的三個參數: url, postData, headers  
        string url = "http://127.0.0.1:8000/WebDemo1/Servlet";
        byte[] post_data;
        Hashtable headers;   //System.Collections.Hashtable  
        string str_params;
        str_params = "id=" + id.value + "&" + "name=" + name.value;
        //設置編碼格式爲utf-8
        post_data = System.Text.UTF8Encoding.UTF8.GetBytes(str_params);
        headers = new Hashtable();
        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
        {   //顯示返回數據
            text.value = www_instance.text;
        }
    }

    IEnumerator TestDown() {
        Debug.Log("進入www方法");
        string url = "http://127.0.0.1:8000/WebDemo1/Pic.jpg";
        //發送請求  
        WWW www_instance = new WWW(url);
        //web服務器返回  
        yield return www_instance;
        if (www_instance.error != null)
        {
            Debug.Log(www_instance.error);
        }
        else
        {   //顯示下載的圖片
            Pic.mainTexture = www_instance.texture;
        }
    }
}

總結

通過unity中www類,就可以和後臺服務器進行數據的交互,可以達到數據之間相互的傳輸,可以應用到網頁遊戲等一些聯網遊戲,也可以完成登陸功能:訪問服務器再傳遞到數據庫,做出判斷再向上逐級返回,完成一個完整的流程。


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