The links you can get on google and stackoverflow are very old (2009).
Between 2009 and today, a lot of things have been solved / improved.
So my question is: how to get/set cookies using UnityWebRequest
with the latest Unity version?
The links you can get on google and stackoverflow are very old (2009).
Between 2009 and today, a lot of things have been solved / improved.
So my question is: how to get/set cookies using UnityWebRequest
with the latest Unity version?
You can use SetRequestHeader and GetRequestHeader/GetResponseHeader to set and get cookies on your WebRequest.
//the key is case sensitive
UnityWebRequest.SetRequestHeader("Cookie", "Delicious cookies");
UnityWebRequest.GetRequestHeader("Cookie");
Thanks to rider, here's my working code: in the foreach
loop you can get all the values, hence I got the Set-Cookie
value I needed.
foreach (var s in www.GetResponseHeaders()) {
Debug.Log("s=" + s);
}
Actually it depends on the Plattform you are targetting with Unity.
In WebGL you cannot set the cookie header directly, as it is restricted for security reasons. If you use WebGL and you need to set the Cookie header for example because you use passport.js for login reasons, then you have to build your whole project and override the javascript function that is called
fetch(url,options);
Add Cookie Header for WebGL Unity Build
In this article you can read how this is done for Unity 2021.3ff Be aware that old Unity Versions used XMLHttpRequest so there is a lot of outdated information out there. fetch basically replaced the XMLHttpRequest, so you can ignore it and override fetch instead by adding this script to your html index file:
<skript>
fetch = function( url,data) {
console.log("url received: " + url);
if (url.indexOf('https://www.replacethatwithyourserveraddress.com/') === 0 || url.indexOf('http://localhost:4000') === 0 || url.indexOf('http://127.0.0.1:4000') === 0) {
data = {...data, ...{credentials : "include"}};
console.log("withCredentials set to true " + JSON.stringify(data) + " url: " + url );
} else {
console.log("withCredentials NOT SET for URL: " + url);
}
return originalfetch(url,data);
};
</skript>