基于WWW的get请求Demo

来源:互联网 发布:最全家庭网络个人投资 编辑:程序博客网 时间:2024/04/30 20:24

开发先知:点击打开链接

开发工具:Unity、VS2010


打开VS,新建项目

选择web-web应用程序


右键项目,按如下图添加一般处理程序


在Handler.ashx.cs修改代码如下:

using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace WebApplication{    /// <summary>    /// Handler1 的摘要说明    /// </summary>    public class Handler1 : IHttpHandler    {        public void ProcessRequest(HttpContext context)        {            context.Response.ContentType = "text/plain";            string name = context.Request.QueryString["name"];            string address = context.Request.QueryString["address"];            if (string.IsNullOrEmpty(name) && string.IsNullOrEmpty(address))            {                context.Response.Write("姓名或地址为空");            }            else            {                if (name == "JiBu" && address == "GanZhou")                {                    context.Response.Write("输入正确");                }                else                {                    context.Response.Write("输入错误");                }            }        }        public bool IsReusable        {            get            {                return false;            }        }    }}

按上篇文章配置好网站,将物理路径添加到web文件内

打开浏览器,输入网址http://www.text.com/Handler1.ashx?name=JiBu&address=GanZhou

网页出现如下图表明成功:


如果报错很可能是如下原因:

1.可能你的物理路径目录权限问题,把该目录权限设置为everyone

2.C:\Windows\System32\drivers\etc目录,在目录下找到hosts文件,打开文件,添加字段127.0.0.1 www.text.com

3.按如下图将目录应用起来,不然访问不到


4.最晕的一个问题,出现如下图报错----未能创建类型


我暂时未能查找到问题所在

但是我换个编译器2010(之前使用的是VS2012)就完事了


接下来介绍在unity中使用www方式与web服务器进行数据请求

添加代码,将其挂载在main camera

using UnityEngine;using System.Collections;using UnityEngine.UI;public class GetObj : MonoBehaviour {    public InputField nameInput;    public InputField addressInput;public void OnBtnLogin()    {        string name = null;        name = nameInput.text;        string address = null;        address = addressInput.text;        StartCoroutine(Request(name,address));    }    IEnumerator Request(string name,string address)    {        string url = "www.text.com/Handler1.ashx?name=" + name + "&address" + address;        WWW www = new WWW(url);        yield return www;        while (!www.isDone)        {            yield return new WaitForEndOfFrame();        }        if (www.error==null)        {            //打印出get请求回应内容            Debug.Log(www.text);        }    }}

在unity中简单建如下图UI:


当点击按钮后,将打印出结果

OK!简单介绍到这里,如果对你有帮助,请多多关注大笑


1 0