Unity: Use HTTP PUT in Unity3D

落花浮王杯 提交于 2019-12-04 06:26:27

If you're not looking for a 3rd party plugin and assuming your server supports it then one method you could look at using is the "X-HTTP-Method-Override" HTTP header. Your client sends the data to the server via POST, but the server handles this as the value in the X-HTTP-Method-Override header (such as PUT).

I've used this before to great effect where our server supported it. An example of using this in Unity3d would be along the lines of:

string url = "http://yourserver.com/endpoint";
byte[] body = Encoding.UTF8.GetBytes(json);    

Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add( "Content-Type", "application/json" );
headers.Add( "X-HTTP-Method-Override", "PUT" );
WWW www = new WWW(url, body, headers);

I recommend looking at BestHTTP package instead of default WWW class. It's cheap (almost all Unity3d assets are, compared to typical middleware prices in game industry) and it's pretty decent, judging by personal experience.

Alternatively, you can use standard .NET sockets.

I made it worked by the following codes using HttpWebRequest

void updatePlayer(){
    var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourAPIUrl");
    httpWebRequest.ContentType = "text/json";
    httpWebRequest.Method = "PUT";

    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = "{" +
            "'ID': '100'," +
            "'ClubName': 'DEF'," +
            "'Number': 102," +
            "'Name': 'AnNT'," +
            "'Position': 'GK'," +
            "'DateOfBirth': '2010-06-15T00:00:00'," +
            "'PlaceOfBirth': 'Hanoi'," +
            "'Weight': 55," +
            "'Height': 1.55," +
            "'Description': 'des'," +
            "'ImageLink': 'annt.png'," +
            "'Status': false," +
            "'Age': '12'" +
            "}";            
        streamWriter.Write(json);
    }
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var responseText = streamReader.ReadToEnd();
        //Now you have your response.
        //or false depending on information in the response
        Debug.Log(responseText);            
    }   
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!