C# unity GET/POST 包装器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8951489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unity GET/POST Wrapper
提问by PandemoniumSyndicate
This is a Unity3d in C# question. The goal is to create an object such that I can pass in a URL and receive data via GET, an object that I would create the would be a wrapper for the WWW logic. I would also like a 'POST' object too, where I could supply a url and a 'Dictionary' of key-value pairs as the post arguements. Sooo... we ultimately would like something like this:
这是 C# 问题中的 Unity3d。目标是创建一个对象,以便我可以传入 URL 并通过 接收数据GET,我将创建的对象将是 WWW 逻辑的包装器。我也想要一个“POST”对象,我可以在其中提供一个 url 和一个键值对的“字典”作为帖子争论。Sooo ......我们最终想要这样的东西:
get_data = GET.request("http://www.someurl.com/somefile.php?somevariable=somevalue");
AND
和
post_data = POST.request("http://www.someurl.com/somefile.php", post)
// Where post is a Dictionary of key-value pairs of my post arguments.
To try and accomplish this, I use the WWWobject. Now, in order to give the WWWobject time to download, we need to have this happening inside a MonoBehaviourobject and yieldthe results. So I got this, which works:
为了尝试实现这一点,我使用了WWW对象。现在,为了让WWW对象有时间下载,我们需要在MonoBehaviour对象和yield结果中发生这种情况。所以我得到了这个,它有效:
public class main : MonoBehavior
{
IEnumerator Start()
{
WWW www = new WWW("http://www.someurl.com/blah.php?action=awesome_stuff");
yield return www;
Debug.Log(www.text);
}
}
What I really want is this:
我真正想要的是:
public class main : MonoBehavior
{
IEnumerator Start()
{
GET request = new GET("http://www.someurl.com/blah.php?action=awesome_stuff");
Debug.Log(request.get_data()); // Where get_data() returns the data (which will be text) from the request.
}
}
Now I have the main script attached to the single GameObjectin the hierarchy (called root). Do I need to have the GETscript attached to the root GameObjectas well? Can I do that dynamically from main?
现在我将主脚本附加到GameObject层次结构中的单个(称为根)。我是否还需要将GET脚本附加到根目录GameObject?我可以动态地做到这一点main吗?
Ultimately, I need a solution that allows me to easily send GETand POSTrequests.
最终,我需要一个可以让我轻松发送GET和POST请求的解决方案。
Cheers!
干杯!
采纳答案by PandemoniumSyndicate
Ah, Got it!
啊,明白了!
My problem was a misunderstanding of how MonoBehaviour and Coroutines worked. The solution is very simple.
我的问题是对 MonoBehaviour 和 Coroutines 的工作方式的误解。解决方法很简单。
In the editor, make an empty GameObject. I named it DB. Then attach the following script to it:
在编辑器中,创建一个空的 GameObject。我将其命名为 DB。然后将以下脚本附加到它:
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
class DB : MonoBehaviour
{
void Start() { }
public WWW GET(string url)
{
WWW www = new WWW(url);
StartCoroutine(WaitForRequest(www));
return www;
}
public WWW POST(string url, Dictionary<string, string> post)
{
WWWForm form = new WWWForm();
foreach (KeyValuePair<String, String> post_arg in post)
{
form.AddField(post_arg.Key, post_arg.Value);
}
WWW www = new WWW(url, form);
StartCoroutine(WaitForRequest(www));
return www;
}
private IEnumerator WaitForRequest(WWW www)
{
yield return www;
// check for errors
if (www.error == null)
{
Debug.Log("WWW Ok!: " + www.text);
}
else
{
Debug.Log("WWW Error: " + www.error);
}
}
}
Then, in your main script's start function, you can do this!
然后,在主脚本的 start 函数中,您可以执行此操作!
private DB db;
void Start()
{
db = GameObject.Find("DB").GetComponentInChildren<DB>();
results = db.GET("http://www.somesite.com/someAPI.php?someaction=AWESOME");
Debug.Log(results.text);
}
Haven't tested the POST requests, but now all the logic is wrapped up! Send HTTP requests to your hearts desire, cheers!
还没有测试 POST 请求,但现在所有的逻辑都被包装了!发送 HTTP 请求到你心中的愿望,干杯!
回答by jmpp
What is that GET script that you're referring to? The WWW class allows you to retrieve GET data just fine, the information you need is in the text property of the instantiated WWW object. Here's the documentation:
您所指的 GET 脚本是什么?WWW 类允许您很好地检索 GET 数据,您需要的信息在实例化的 WWW 对象的 text 属性中。这是文档:
http://unity3d.com/support/documentation/ScriptReference/WWW-text.htmlhttp://unity3d.com/support/documentation/ScriptReference/WWW.html
http://unity3d.com/support/documentation/ScriptReference/WWW-text.htmlhttp://unity3d.com/support/documentation/ScriptReference/WWW.html
All you need to do is yield the WWW object, as you're doing just now, and then read any of the properties you're interested in, plain and simple, no extra classes needed.
您需要做的就是产生 WWW 对象,就像您刚才所做的那样,然后读取您感兴趣的任何属性,简单明了,不需要额外的类。
As for sending a POST object, that's what the WWWForm class is for:
至于发送 POST 对象,这就是 WWWForm 类的用途:
http://unity3d.com/support/documentation/ScriptReference/WWWForm.html
http://unity3d.com/support/documentation/ScriptReference/WWWForm.html
In short, you just create a WWWForm object, add fields to it through AddField(), and then simply construct a new WWW object with the POST URL & the former object, that's it. Yield the WWW object and once it comes back you're data has been submitted. Responses are, again, in the text property & errors in the corresponding field. Plain, clean & simple.
简而言之,您只需创建一个 WWWForm 对象,通过 AddField() 向其中添加字段,然后简单地使用 POST URL 和前一个对象构造一个新的 WWW 对象,就是这样。生成 WWW 对象,一旦它返回,您的数据就已提交。响应再次出现在相应字段中的文本属性和错误中。朴素、干净、简单。
HTH!
哼!
回答by questionman
Here is @pandemoniumsyndicate's code modified to add a callback. The original code is not completely correct, since the GETand POSTfunctions will exit immediately after calling the coroutine. At that time it is likely that the WWWrequest is not yet complete and accessing any field except (www.isDone) is pointless.
这是@pandemoniumsyndicate 的修改代码以添加回调。原始代码并不完全正确,因为GET和POST函数会在调用协程后立即退出。那时很可能WWW请求还没有完成,访问除 ( www.isDone)之外的任何字段都是没有意义的。
The following code defines a delegate, WWWRequestFinished, which will be called when the request is finished with the result of the request and data received, if any.
下面的代码定义了一个委托,WWWRequestFinished当请求完成时将调用它并接收到请求的结果和数据(如果有)。
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class WWWRequestor : MonoBehaviour
{
Dictionary<WWW, object> mRequestData = new Dictionary<WWW, object>();
public delegate void WWWRequestFinished(string pSuccess, string pData);
void Start() { }
public WWW GET(string url, WWWRequestFinished pDelegate)
{
WWW aWww = new WWW(url);
mRequestData[aWww] = pDelegate;
StartCoroutine(WaitForRequest(aWww));
return aWww;
}
public WWW POST(string url, Dictionary<string, string> post, WWWRequestFinished pDelegate)
{
WWWForm aForm = new WWWForm();
foreach (KeyValuePair<String, String> post_arg in post)
{
aForm.AddField(post_arg.Key, post_arg.Value);
}
WWW aWww = new WWW(url, aForm);
mRequestData[aWww] = pDelegate;
StartCoroutine(WaitForRequest(aWww));
return aWww;
}
private IEnumerator WaitForRequest(WWW pWww)
{
yield return pWww;
// check for errors
string aSuccess = "success";
if (pWww.error != null)
{
aSuccess = pWww.error;
}
WWWRequestFinished aDelegate = (WWWRequestFinished) mRequestData[pWww];
aDelegate(aSuccess, pWww.text);
mRequestData.Remove(pWww);
}
}

