Unity GET/POST包装器

Pan*_*ate 17 c# post get unity-game-engine web

这是C#问题中的Unity3d.目标是创建一个对象,以便我可以传入一个URL并通过GET一个对象来创建,这个对象我将创建WWW逻辑的包装器.我也想要一个'POST'对象,在那里我可以提供一个url和一个键值对的'Dictionary'作为帖子争论.Sooo ...我们最终想要这样的事情:

get_data = GET.request("http://www.someurl.com/somefile.php?somevariable=somevalue");
Run Code Online (Sandbox Code Playgroud)

post_data = POST.request("http://www.someurl.com/somefile.php", post)
// Where post is a Dictionary of key-value pairs of my post arguments. 
Run Code Online (Sandbox Code Playgroud)

为了尝试实现这一点,我使用了该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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我真正想要的是这个:

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.   
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我将主脚本附加到GameObject层次结构中的单个(称为root).我是否还需要将GET脚本附加到根目录GameObject?我能动态地做到main吗?

最终,我需要一个允许我轻松发送GETPOST请求的解决方案.

干杯!

Pan*_*ate 17

啊,明白了!

我的问题是对MonoBehaviour和Coroutines如何工作的误解.解决方案非常简单.

在编辑器中,创建一个空的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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,在主脚本的启动功能中,您可以执行此操作!

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);
}
Run Code Online (Sandbox Code Playgroud)

还没有测试过POST请求,但是现在所有的逻辑都被包裹了!向您的心中发送HTTP请求,欢呼!

  • 我不认为这实际上有效.当您这样做时:StartCoroutine(WaitForRequest(request))Debug.Log(request.text)如果请求尚未完成,则只会停止协程,而不是实际的功能.在请求完成之前将调用哪个Debug.Log(request.text). (2认同)