Bri*_*ham 6 rest http put unity-game-engine
我是Unity的新手,在Unity中遇到RESTFul的一些问题.我想使用HTTP PUT更新服务器上的一些数据,但正如我在搜索网络时收到的那样,Unity中的WWWW类不支持HTTP PUT.我还尝试了一些与HTTP PUT相关的HttpWebRequest示例,但总是收到错误代码400:错误请求.
我怎么解决这个问题?我是否必须在更新时列出所有键值对,或者只需要列出我想要更改值的对?
如果您不是在寻找第三方插件并假设您的服务器支持它,那么您可以使用的一种方法是"X-HTTP-Method-Override"HTTP标头.您的客户端通过POST将数据发送到服务器,但服务器将此处理为X-HTTP-Method-Override标头中的值(例如PUT).
我之前使用过这个,效果很好,我们的服务器支持它.在Unity3d中使用它的一个例子是:
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);
Run Code Online (Sandbox Code Playgroud)
我使用 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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5956 次 |
| 最近记录: |