You can do this with reflection. Unfortunately, none of the C# answers from similar questions works because Unity is using Mono and their variable names are totally different making GetField
unable to find the variable that's holding the headers.
Dump all the headers in the HttpWebRequest
class with HttpWebRequest.GetType().GetFields
then look for the name of the field that holds the headers. In my test, the field name is "webHeaders"
and is a type of WebHeaderCollection
.
Below is an extension method that modifies that "webHeaders"
from reflection:
public static class ExtensionMethods
{
public static void changeSysTemHeader(this HttpWebRequest request, string key, string value)
{
WebHeaderCollection wHeader = new WebHeaderCollection();
wHeader[key] = value;
FieldInfo fildInfo = request.GetType().GetField("webHeaders",
System.Reflection.BindingFlags.NonPublic
| System.Reflection.BindingFlags.Instance
| System.Reflection.BindingFlags.GetField);
fildInfo.SetValue(request, wHeader);
}
public static void changeReflectionField(this HttpWebRequest request, string fieldName, object value)
{
FieldInfo fildInfo = request.GetType().GetField(fieldName, System.Reflection.BindingFlags.NonPublic
| System.Reflection.BindingFlags.Instance
| System.Reflection.BindingFlags.GetField);
fildInfo.SetValue(request, value);
}
}
USAGE:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://1.1.1.1");
//Change Host header
request.changeSysTemHeader("Host", "xyz.net");
request.changeReflectionField("hostChanged", true);
WebResponse response = request.GetResponse();
This should work for any restricted header like User-Agent
. Tested with Unity 2017.2. Mentioned the Unity version and how I found the field name so that when the variable name changes in the future, anyone can simply fix it.