Hi I am trying to implement a "PUT" request to send JSON string to my server, below is my code
public static string PUT (string url, string jsonStr){
string msg = "";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "PUT";
ServicePointManager.Expect100Continue = false;
using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream())){
sw.Write(jsonStr);
sw.Flush();
sw.Close();
}
try{
HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse;
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
msg = streamReader.ReadToEnd();
}
}catch(WebException ex){
msg = ex.Message;
}
return msg;
}
Right now I can receive msg from my server like "Success!" which is pretty short. But I wonder if this method should be written as a coroutine and do like "yield return response" or "yield return streamReader.EndofStream()" to ensure reading the response after all messages have been got from server.
I am using Unity3D which has its own web request method - "UnityWebRequest", it needs "yield return unityWebRequest.send()" to wait until request completed. That's why I think maybe HttpWebRequest also needs that.
Does HttpWebResponse needs yield/coroutine to wait for message from server?
No.
But I wonder if this method should be written as a coroutine and do like "yield return response" or "yield return streamReader.EndofStream()" to ensure reading the response after all messages have been got from server.
You can use coroutine/yiled with WWW and UnityWebRequest. You can learn more about UnityWebRequest here.
For HttpWebResponse
, you have to use it in another Thread
or use the asynchronous version of it. Here is an example. If you don't do this, expect your game to be freezing most of the time, especially when you are receiving large data.