- Home /
How to consume a php webservice in Unity ?
Hi,
I'm actually maling a sample to test the web service consumption into Unity. In my localhost I've created a little php webservice : index.php :
class Donne
{
function donne($i)
{
return $i;
}
function hello()
{
return "hello world";
}
function add($a, $b)
{
$c = $a + $b;
return $c;
}
}
try
{
$server = new SoapServer(null, array('uri' => 'http://127.0.0.1/webservices/index.php'));
$server->setClass("Donne");
$server->handle();
}
catch(Exception $e)
{
echo "Exception: " . $e;
}
?>
And I created an other page to use it : test.php
<?php
try
{
$clientSOAP = new SoapClient( null,
array (
'uri' => 'http://127.0.0.1/webservices/index.php',
'location' => 'http://127.0.0.1/webservices/index.php',
'trace' => 1,
'exceptions' => 0
));
$ret = $clientSOAP->__call('hello', array());
echo $ret;
echo '<br />';
if (isset($_GET['a']) && isset($_GET['b']))
{
$ret = $clientSOAP->__call('add', array('a'=>$_GET['a'], 'b'=>$_GET['b']));
echo $ret;
}
else
{
echo 'no';
}
}
catch(SoapFault $f)
{
echo $f;
}
?>
When I acces if from the following URL : (http://127.0.0.1/webservices/test.php?a=5&b=8), I've got the correct answer : Hello World
13
But when I try to access it from the Unity execution :
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class WebService : MonoBehaviour {
public GameObject text;
public string url = "http://127.0.0.1/webservices/test.php";
private WWWForm wwwForm;
private Text m_text;
// Use this for initialization
IEnumerator Start () {
wwwForm = new WWWForm ();
wwwForm.AddField ("a", 5);
wwwForm.AddField ("b", 8);
m_text = text.GetComponent<Text> ();
WWW www = new WWW(url, wwwForm);
yield return www;
m_text.text = www.text;
}
}
I've got "Hello World
no". I've read that all WWWForms are GET by default but the $_GET in php is not valid.
What did I miss ?
Thx for the help.
is it possible you need to sort of add the headers manually, eg http://answers.unity3d.com/answers/675582/view.html
Just BTW you'd surely just use Parse.com or any of the other baas these days, for "cloud" odds and ends
Answer by Bunny83 · Dec 03, 2015 at 03:03 PM
WWWForms is POST by default. Get requests have their parameters / data inside the URL. A GET request can have a body, but it's ignored by the parser since it has no meaning for GET requests. See this.
So either add your parameters to the URL, just like you did in your browser test, or change the serverside code to accept POST requests and use the parsed body data instead.
it's a good idea to just stick with POST change the serverside
All hail to the post method ! That was it.
I check again the Unity doc and I've been lure by the following line : "The WWW class can be used to send both GET and POST requests to the server. The WWW class will use GET by default and POST if you supply a postData parameter."
Thank you !