I am trying to get a Cookie from my server “https://myURL.com”.
void Start(){
UnityWebRequest test = new UnityWebRequest(url);
test.GetRequestHeader(“Cookies”);
}
I keep getting a null value. Is there other way to get the cookies from my browser?
There are several things that should be cleared up here. First of all you have to differentiate between the request and the response part. You can set request headers and you will receive response headers,
So reading request headers doesn’t make that much sense since the request headers are the headers you have to set. So the headers you want to send along with the request. The response headers are the headers that the server returned.
Next thing is there are two different headers:
- the Cookie request header
- and the Set-Cookie response header
You can read more about that over here.
You as a client if you want to send a cookie to the server you have to set the “Cookie” header. There’s no “Cookies” header. All cookies that should be send to the server have to be accumulated in a single Cookie header. On the other hand if you want to read the cookie information that the server send out and wants you to remember, you have to read the “Set-Cookie” header(s) that the server included in his response.
Unfortunately many HTTP clients, Unity’s UnityWebRequest included, do represent the HTTP headers with a dictionary. This is a problem because in case the server want to set multiple cookies in one response you can only receive one of them. This is a general design flaw because HTTP does allow certain headers to appear multiple times in a response and Set-Cookie is one of them.
So to read / get the cookie that a server may have send to you, you have to read the response headers either with GetResponseHeader or with GetResponseHeaders and look for the “Set-Cookie” header. As xxmariofer said, of course reponse headers can only be read once the reponse from the server had arrived.
If you want to send the cookie information you may have received previously along with your next request, you have to set the Cookie request header.
thats weird, since it should return an empty string not a null value, anywaym dont you have to send the request before getting the header?
IEnumerator Start()
{
UnityWebRequest test = new UnityWebRequest(url);
yield return test.SendWebRequest();
test.GetRequestHeader("Cookies");
}