Unity: Use HTTP PUT in Unity3D

I am brand new to Unity and ran into some problems in RESTFul in Unity. I want to update some data on the server using HTTP PUT, but like what I got when searching the Internet, WWWW class in Unity does not support HTTP PUT. I also tried the HttpWebRequest example associated with the HTTP PUT, but always got the 400: Bad Request error code.

How can I solve this problem? Do I have to list all key-value pairs during the upgrade, or do I just need to specify the pairs that I want to change?

+6
source share
3 answers

I processed it using 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); } } 
0
source

If you are not looking for a third-party plugin and assume that your server supports it, then one of the methods you can use when using is the HTTP header "HTTP override method". Your client sends data to the server via POST, but the server treats this as the value in the X-HTTP-Method-Override header (e.g. PUT).

I have used this before to use our server efficiently. An example of using this in Unity3d would be as follows:

 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); 
+7
source

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

Alternatively, you can use standard .NET sockets .

+1
source

Source: https://habr.com/ru/post/985243/


All Articles