Unity GET/POST Wrapper

Ah, Got it!

My problem was a misunderstanding of how MonoBehaviour and Coroutines worked. The solution is very simple.

In the editor, make an empty GameObject. I named it DB. Then attach the following script to it:

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!

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!


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:

http://unity3d.com/support/documentation/ScriptReference/WWW-text.html http://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.

As for sending a POST object, that's what the WWWForm class is for:

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.

HTH!


Here is @pandemoniumsyndicate's code modified to add a callback. The original code is not completely correct, since the GET and POST functions will exit immediately after calling the coroutine. At that time it is likely that the WWW request is not yet complete and accessing any field except (www.isDone) is pointless.

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.

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);
    }

}

Comments

  1. Lopez

    • 2016/7/10

    Ah, Got it! My problem was a misunderstanding of how MonoBehaviour and Coroutines worked. The solution is very simple.

  2. Morgan

    • 2020/2/9

    In the editor, make an empty GameObject. I named it DB. Then attach the following script to it: 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();

  3. Jared

    • 2018/10/10

    Unity GET/POST Wrapper. Ceci est une question Unity3d en C #. L'objectif est de créer un objet tel que je puisse passer une URL et recevoir des données via 

  4. Kelly

    • 2015/5/23

    Unity php POST. UnityWebRequest POST to PHP not work, Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, An overload of UnityWebRequest.POST accepts, as a second parameter, a List argument, whose members must all be IMultipartFormSections.

  5. Finnley

    • 2020/9/24

    Это вопрос Unity3d в C #. get_data = GET.request("http://www.someurl.com/somefile.php?somevariable=somevalue"); А ТАКЖЕ post_data = c# web get post unity3d.

  6. Ayan

    • 2018/9/5

    - GitHub - Sonic853/WebServicesForUnity: Simple Get / Post / Put C# wrapper for the UnityWebRequest in Unity 3D. Simple Get / Post / Put C# wrapper for the UnityWebRequest in Unity 3D. Skip to content

  7. Dane

    • 2021/3/26

    Unity GET/POST Wrapper. Este é um Unity3d em questão C #. O objetivo é criar um objeto de tal forma que eu possa passar em uma URL e receber dados via GET 

  8. De Luca

    • 2020/10/6

    Unity. Unity Wrapper for Intel RealSense SDK 2.0 allows Unity developers to add streams from Intel RealSense Cameras to their scenes using provided textures. We aim to provide an easy to use prefab which allows device configuration, and texture binding using the Unity Inspector, without having to code a single line of code. Using this wrapper, Unity developers can get a live stream of Color, Depth and Infrared textures.

  9. Adams

    • 2018/10/15

    Unity GET / POST Wrapper. 17. Это вопрос Unity3d в С#. Цель состоит в том, чтобы создать объект, чтобы я мог передавать URL-адрес и получать данные через 

  10. Leone

    • 2018/3/27

    Get the Input Wrapper package from LunaArgenteus and speed up your game development process. Find this & other Input Management options on the Unity Asset Store.

  11. Zyaire

    • 2015/12/3

    Unity GET/POST Wrapper. Ini adalah Unity3d dalam pertanyaan C #. Tujuannya adalah untuk membuat objek sehingga saya dapat mengirimkan URL dan menerima data 

  12. Aldo

    • 2017/3/26

    A handy wrapper for the Unity WebRequest system. Contribute to dubit/unity-http development by creating an account on GitHub.

  13. Conner

    • 2018/9/13

    Unity GET/POST Wrapper. Đây là một Unity3d trong câu hỏi C #. Mục tiêu là tạo ra một đối tượng sao cho tôi có thể truyền URL và nhận dữ liệu qua GET 

  14. Bellamy

    • 2018/2/20

    Did you find this page useful? Please give it a rating: Thanks for rating this page! Report a problem on this page.

  15. Henrik

    • 2015/8/24

    Unity GET/POST Wrapper. Questa è una domanda di Unity3d in C #. L'obiettivo è creare un oggetto tale che possa passare in un URL e ricevere dati tramite GET 

  16. Jayceon

    • 2020/7/17

    WebServicesForUnity. Simple Get / Post / Put C# wrapper for the UnityWebRequest in Unity 3D. How To Use: Copy the "WebService.cs" files and "SimpleJSON" 

Comments are closed.

Recent Posts