WWW exception in 2017.1 but not 5.6

The following code used to work great in 5.5 and 5.6 but is now throwing an exception in 2017.1. I’m trying to figure out if I’m just fundamentally doing something wrong that happened to work in 5.6 but now fails in 2017.1 or if this is a Unity bug.

private static readonly string contentType = “Content-Type”;
private static readonly string contentLength = “Content-Length”;

internal static WWW PostJsonToURL(string uploadText, string postURL)
{
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Dictionary<string, string> postHeader = new Dictionary<string, string>();

postHeader.Add(contentType, “text/json”);
postHeader.Add(contentLength, uploadText.Length.ToString());

WWW request = new WWW(postURL, encoding.GetBytes(uploadText), postHeader);
return request;
}

when I run this in 2017.1 I get this exception in the WWW constructor:

InvalidOperationException: Cannot override system-specified headers
UnityEngine.Networking.UnityWebRequest.SetRequestHeader (System.String name, System.String value) (at C:/buildslave/unity/build/artifacts/generated/common/modules/UnityWebRequest/WebRequestBindings.gen.cs:471)
UnityEngine.WWW…ctor (System.String url, System.Byte[ ] postData, System.Collections.Generic.Dictionary`2 headers) (at C:/buildslave/unity/build/Runtime/WebRequestWWW/UWRWWW.cs:62)

Any advice?

My guess is that it’s not allowing you to override the Content-Length header. It’s probably setting that automatically internally (as it really should be anyway).

In 2017.1 WWW class was rewritten to be a wrapper on top of UnityWebRequest. This imposes a more strict rules for headers you can set, specifically not allowing to set headers that are either set automatically of can cause problems.
The Content-Type is set automatically to correct value and should not be set manually. Even in old WWW implementation setting this header was asking for trouble.

2 Likes

Thanks for the help. That worked. Removing Content-Length fixed my issue.

3 Likes