Skip to content

Instantly share code, notes, and snippets.

@MadsBogeskov
Created April 27, 2016 12:59
Show Gist options
  • Save MadsBogeskov/811896a1e6d0b001fad4a4a6c290587c to your computer and use it in GitHub Desktop.
Save MadsBogeskov/811896a1e6d0b001fad4a4a6c290587c to your computer and use it in GitHub Desktop.
The builtin WWW.responseHeaders property does not return all actual headers. E.g. if a request has multiple 'Set-Cookies' then the native will only return one of them. This is because the builtin function returns a Dictionary<string, string> which cannot have multiple keys with the same name. This extension to the WWW class makes it possible to …
using UnityEngine;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Linq;
using System.Collections.Generic;
/// <summary>
/// Extensions for the WWW class
/// </summary>
public static class WWWExtension
{
/// <summary>
/// Get all response headers
/// </summary>
/// <param name="www">The WWW instance</param>
/// <returns>All response headers for a request</returns>
public static IEnumerable<KeyValuePair<string, string>> ResponseHeaders(this WWW www)
{
var propertyName = "responseHeadersString";
var property = typeof(WWW).GetProperty(propertyName, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance);
if (property == null)
{
Debug.LogWarning("The Unity SDK might have changed so that the WWW class no longer has a " + propertyName + " property.");
return null;
}
var headers = property.GetValue(www, null) as string;
headers.Split('\n');
var headerRegex = new Regex(@"(.*?):\s(.*)");
var splitRegex = new Regex(": ");
return headerRegex.Matches(headers).Cast<Match>().Select(x => splitRegex.Split(x.Value)).Select(x => new KeyValuePair<string, string>(x[0], x[1]));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment