Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

UnityWebRequest GET with request body

Discussion in 'Scripting' started by sramos_eurecat, Jan 8, 2016.

  1. sramos_eurecat

    sramos_eurecat

    Joined:
    Oct 28, 2015
    Posts:
    6
    Hi,
    I need to access a REST API from Unity and some of the GET requests require a body. This is because these services perform queries that can accept parameters, and these are too complex to be passed on the URL.

    I have tried to assign an UploadHandler to the request, but it looks like the body is not being sent to the server. I would like to know if the UploadHandler is always being ignored when executing a GET request, and if so, is there any other way I could do this?

    Here's my GET coroutine:

    Code (CSharp):
    1. protected IEnumerator ExecuteGet(string resource, string jsonData)
    2. {
    3.         string url = getEndpoint() + resource;
    4.         UnityWebRequest request = UnityWebRequest.Get(url);
    5.         request.SetRequestHeader("Content-Type", "application/json");
    6.  
    7.         if (jsonData != null)
    8.         {
    9.             byte[] data = System.Text.Encoding.UTF8.GetBytes(jsonData);
    10.             UploadHandlerRaw upHandler = new UploadHandlerRaw(data);
    11.             upHandler.contentType = "application/json";
    12.             request.uploadHandler = upHandler;
    13.         }
    14.      
    15.         yield return request.Send();
    16. }
    Thank you.
     
  2. Cripple

    Cripple

    Joined:
    Aug 16, 2012
    Posts:
    92
    Same here, I tried to achieve the same stuff without any success.
    Don't have too much time to try more on it, I will wait for someone else answer :)

    Cheers !
     
    bkldavey likes this.
  3. eisenpony

    eisenpony

    Joined:
    May 8, 2015
    Posts:
    971
    GET requests are not intended to have a body. Although it does not break the specifications since any HTTP operations is technically allowed to include a body payload, it goes against the recommendations. For that reason, I doubt the unity framework has built in support for including a body in GET requests.

    Further reading:
    http://stackoverflow.com/questions/978061/http-get-with-request-body
     
    Bunny83 likes this.
  4. sramos_eurecat

    sramos_eurecat

    Joined:
    Oct 28, 2015
    Posts:
    6
    Thanks for the answer @eisenpony. Indeed, GET requests with a body don't seem to be supported so I ended up modifying the server side. I could finally encode all the filters in a way so that they can be passed as URL parameters.

    Now I have encountered another issue though. I wanted to send a POST request with json as a body and this doesn't work either. I tried the same code as above but with the following modification:
    Code (CSharp):
    1. UnityWebRequest request = UnityWebRequest.Post(url, jsonData);
    Unfortunately it looks like the method doesn't accept raw data. According to the documentation:
    (Source: http://docs.unity3d.com/ScriptReference/Experimental.Networking.UnityWebRequest.Post.html)

    On the other hand PUT requests do accept it. I find it weird that this is not supported for POST as well.

    So my only choice seems to be to switch back to WWW, unless somebody knows of a workaround for this.
     
  5. MarioRuiz

    MarioRuiz

    Joined:
    Nov 7, 2009
    Posts:
    161
    since you control both client and server side is it too difficult for you to send the json data in a wwwForm? if it is could you explain why?
     
  6. sramos_eurecat

    sramos_eurecat

    Joined:
    Oct 28, 2015
    Posts:
    6
    Yep @MarioRuiz, that would be the other obvious solution. The only reason I would rather not do it (besides having to change all the methods on the server, since we have quite a few) is uniformity. I want to keep things simple and so I don't like the idea of having to encode things differently depending on whether I am updating or creating an object, it just complicates more the code. But I also don't like having to switch to WWW now, so.... I guess I'll have to give it a try. I was just reading about how to handle form parameters with Spring, which is what I am using on the server side :)
     
    MarioRuiz likes this.
  7. McSwan

    McSwan

    Joined:
    Nov 21, 2013
    Posts:
    127
    Hi, Took a while but this worked for me:

    The Json in my example doesn't have quotes around type - maybe that is why it wasn't working.
    Code (CSharp):
    1.  WWWForm form = new WWWForm();
    2.         // Username - this is irrelevent - needed for post request
    3.         form.AddField("username", "name");
    4.  
    5.  
    6.         UnityWebRequest wwwSignin = UnityWebRequest.Post(URL, form);
    7.         Debug.Log("URL:" + URL);
    8.  
    9.         string jsonData = "";
    10.         jsonData = "{Username:\"Pants\",Password:\"PantsLoveMe\"}";
    11.  
    12.         if (jsonData != null)
    13.         {
    14.             byte[] data = System.Text.Encoding.UTF8.GetBytes(jsonData);
    15.  
    16.             UploadHandlerRaw upHandler = new UploadHandlerRaw(data);
    17.             upHandler.contentType = "application/json";
    18.             wwwSignin.uploadHandler = upHandler;
    19.         }
    20.      
    21.         yield return wwwSignin.Send();
    22.  
    23.         if (wwwSignin.isError)
    24.         {
    25.             Debug.Log(wwwSignin.error);
    26.         }
    27.         else
    28.         {
    29.             // Show results as text
    30.             Debug.Log("Returning:" + wwwSignin.downloadHandler.text);
    31.  
    32.  
    33.             //JSONObject j = new JSONObject(wwwSignin.downloadHandler.text);
    34.          
    35.         }
     
  8. sramos_eurecat

    sramos_eurecat

    Joined:
    Oct 28, 2015
    Posts:
    6
    Hi McSwan. So with your solution both the form and the json are being sent in the request? I had tried sending either raw data or a form, but not both at the same time. Maybe that's the way to trick it.
    I have it working now with the form solution but I will definitely give it a try. Thank you!
     
  9. RD3_Elizeu

    RD3_Elizeu

    Joined:
    Jul 2, 2021
    Posts:
    8
    Has this changed since then? I don't control the server side and there is a GET request that has a request body that must be filled the following way:
    Code (JavaScript):
    1. [
    2.   "string"
    3. ]
    Is it possible to do this using UnityWebRequest?
     
  10. RD3_Elizeu

    RD3_Elizeu

    Joined:
    Jul 2, 2021
    Posts:
    8
    After 5 minutes of posting the question i managed to do it :oops:

    My solution was the following:

    Code (CSharp):
    1.  
    2.     public IEnumerator GetRequestWithBody(string url, string _json)
    3.     {
    4.         using (UnityWebRequest www = UnityWebRequest.Get(url))
    5.         {
    6.             //_json = "[\"" + _string + "\"]";
    7.             www.SetRequestHeader("Content-Type", "application/json");
    8.             www.SetRequestHeader("accept", "text/plain");
    9.             www.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(_json));
    10.             yield return www.SendWebRequest();
    11.             if (www.isNetworkError)
    12.             {
    13.                 Debug.Log(www.error);
    14.             }
    15.             else
    16.             {
    17.                 if (www.isDone)
    18.                 {
    19.                     string jsonResult = System.Text.Encoding.UTF8.GetString(www.downloadHandler.data);
    20.                
    21.                 }
    22.             }
    23.         }
     
    Dominus12 likes this.
  11. VesuvianPrime

    VesuvianPrime

    Joined:
    Feb 26, 2013
    Posts:
    135
    Frustratingly, GET body seems to work with UnityWebRequest from the editor, but I'm getting a null body when running the same code from WebGL
     
  12. Aurimas-Cernius

    Aurimas-Cernius

    Unity Technologies

    Joined:
    Jul 31, 2013
    Posts:
    3,642
  13. VesuvianPrime

    VesuvianPrime

    Joined:
    Feb 26, 2013
    Posts:
    135
    Freaking Javascript! Thanks for the clarification.
     
    ExcaliburGames likes this.
  14. wechat_os_Qy02h7AUZqkoMALRQP1XaCpZ4

    wechat_os_Qy02h7AUZqkoMALRQP1XaCpZ4

    Joined:
    Apr 1, 2020
    Posts:
    1
    how does it work ,Can you show your code