Web service in a button event handler

I want to put a button in my game. When the user presses the button, a request should be sent to a server using a web service.

How can I do that in Unity?

I tried the script given below, but it produces the error “OnGUI() can not be a coroutine”.

#pragma strict

var message : String;

function OnGUI () {        
	if (GUI.Button (Rect (20,40,200,20), "My button")) 
        {
		message = "Client interaction button pressed";
                var url = "http://localhost:8345/rest/ping-pong";
                var form = new WWWForm();
                form.AddField( "message", message);
                var www = new WWW( url, form );
                yield www;
                if (www.error == null) 
                {
                   message = www.text;
                }
                else
                {
                        message = www.error;
                }                
	}

	GUI.Box (Rect (10,10,300,90), message);
}

Update:

I changed the code to

#pragma strict

var message : String;

function OnGUI () {        
	if (GUI.Button (Rect (20,40,200,20), "Client interaction")) {
		message = "Client interaction button pressed";
	}
	else if (GUI.Button (Rect (20,70,200,20), "Server interaction")) {
		print("Server interaction");
		SendRequestToServer();
	}
	
	GUI.Box (Rect (10,10,300,90), message);
}

function SendRequestToServer()
{
        var url = "http://localhost:8345/rest/ping-pong";
        var form = new WWWForm();
        form.AddField( "message", message);
        var www = new WWW( url, form );
        yield www;
        if (www.error == null) 
        {
        	print (www.text);
        }
        else
        {
        	print (www.text);
        }

}

Now I’m getting the error

SecurityException: No valid crossdomain policy available to allow access.

Separate the code that happens when the button is pushed into another function and call that from OnGUI

You need to use StartCoroutine() to call a separate function. See the following documentation:

http://unity3d.com/support/documentation/ScriptReference/MonoBehaviour.StartCoroutine.html