4

I'm trying to do a HTTP Delete request from Unity and bump into the idea of use the HttpRequest class included in the System.Web namespace of .Net

How can I achieve this, I supose that some sort of import of that namespace must be done, but how?

Hope some one can give me some orientation

ASPuma
  • 51
  • 1
  • 1
  • 6
  • Possible duplicate of [Unity3D - can I use .NET 4.5 assembly as external library?](http://stackoverflow.com/questions/20703689/unity3d-can-i-use-net-4-5-assembly-as-external-library) – Lews Therin Jul 28 '16 at 19:42
  • `HttpRequest` is only available in .NET 4.5, but if you did want to do this with the .NET libraries, `HttpWebRequest` has been available since .NET 1.1 and can do what you want. I've not tried to use it from Unity but I don't see why it wouldn't work. – Octopoid Jul 28 '16 at 21:53

2 Answers2

9

HttpClient is only available in 4.5 NET and above and Unity does not use that version. Unity uses about 3.5 .NET version.

If you are using Unity 5.3, UnityWebRequest.Delete can be used to make a Delete request. It can be found in the Experimental.Networking namespace. If you are using Unity 5.4 and above,UnityWebRequestcan be found in the UnityEngine.Networking; namespace.

Full working example:

IEnumerator makeRequest(string url)
{
    UnityWebRequest delReq = UnityWebRequest.Delete(url);
    yield return delReq.Send();

    if (delReq.isError)
    {
        Debug.Log("Error: " + delReq.error);
    }
    else
    {
        Debug.Log("Received " + delReq.downloadHandler.text);
    }
}

Usage:

StartCoroutine(makeRequest("http://www.example.com/whatever"));

Make sure to include using UnityEngine.Networking. You can find complete examples with it here.


EDIT (UPDATE)

Unity now supports .NET 4.5 so you can now use HttpClient if you wish. See this post for how to enable it.

After enabling it, Go to <UnityInstallationDirectory>\Editor\Data\MonoBleedingEdge\lib\mono\4.5 or for example, C:\Program Files\Unity\Editor\Data\MonoBleedingEdge\lib\mono\4.5 on my computer.

Once in this directory, copy System.Net.Http.dll to your <ProjectName>\Assets directory and you should be able to use HttpClient after importing the System.Net.Http namespace. If there are some other error about missing dependencies, you can get the dlls from this path too and copy them to your <ProjectName>\Assets directory too.

Programmer
  • 121,791
  • 22
  • 236
  • 328
  • Hi @Programmer your answer its exactly what my approach its aiming at, I was shooting some arrows there but getting to this point, non the less after putting your code to work I'm getting a 401L error code on delReq after sending, an Unauthorized error? whit the WWW class I pass a Dictionary with authorization headers to log in, how do I achieve that here? – ASPuma Jul 29 '16 at 15:34
  • @ASPuma You use `delReq.SetRequestHeader("Your Header", "Your value");`. Let me know if that solves your problem. – Programmer Jul 29 '16 at 15:39
  • That's all it needs @Programmer some auth, thank you for all your help, my respects! – ASPuma Jul 29 '16 at 15:53
  • I don't suppose you can include an approach that can be used outside the main unity thread? – Basic Dec 14 '16 at 01:00
  • @Basic sorry, can you rephrase that comment? I don't understand it. – Programmer Dec 14 '16 at 01:02
  • I've got a class that doesn't inherit from MonoBehaviour with various things that happen in the background (like maintaining a read-ahead cache to load things from disk). I'd like to extend it to allow it to download content ahead of time too. Since it's not running in the main Unity thread, I can't use any unity engine classes. I seem to be having trouble getting unity to reference any of the Framework classes that would provide me with network connectivity. Is that any clearer? It may justify its own question, but I thought you might know a 1-liner and could expand your (excellent) answer. – Basic Dec 14 '16 at 01:37
  • If you have a class that doesn't doesn't inherit from `MonoBehaviour`, that does not mean that the class is running in another `Thread` unless you explicitly call it's function in another `Thread`. I want to help. If you can create a question and add your code to it, I will take a look at it. – Programmer Dec 14 '16 at 01:45
  • @Basic Just in case I am not clear you may use any C# network API in another Thread but can't use Unity API in the answer above in another Thread. If you decide to use C# network API in another Thread, you can use my Thread Wrapper from [this](https://stackoverflow.com/questions/41330771/use-unity-api-from-another-thread-or-call-a-function-in-the-main-thread/41333540?s=1|41.5690#41333540) answer to simply making calls into main thread from another Thread. – Programmer Oct 20 '17 at 19:28
  • @Programmer Apologies, I had a holiday and this slipped. I was intentionally running some of my code on a non-UI thread - why impact the frame rate with pre-caching?). I ended up implementing my own callback mechanism to let the ui thread invoke arbitrary callbacks. Thanks for following up though, it's appreciated. – Basic Nov 06 '17 at 11:44
  • @Basic *"I had a holiday and this slipped. I was intentionally running some of my code on a non-UI thread"* It's fine to do this. That's how I do my network(TCP/UDP) stuff. *"why impact the frame rate with pre-caching?"* I don't understand this but don't do your network stuff with non Unity API on the main Thread. It's very likely you'll be blocking the main thread. – Programmer Nov 06 '17 at 17:39
  • Yes, thanks, I'm aware. I've been writing multi-threaded apps for decades. Apologies if that wasn't clear. I wasn't referring to a threading issue per-se but rather that I didn't want to use Unity's UI thread to do the download, I wanted to do it myself using native.Net classes which I was unable to reference. In any case, it's no longer an issue, so thanks for your time. – Basic Nov 07 '17 at 03:13
  • Yes, you can use native.Net to do that in another Thread. One disadvantage is that you **can't** build for WebGL platform once you reference any native.Net network stuff or use Thread. If you don't care about WebGL then go ahead. You are welcome! – Programmer Nov 07 '17 at 03:19
  • Does anyone have a suggestion how to include the System.Net.Http package if I get this error: `error CS1070: The type `System.Net.Http.HttpContent' has been forwarded to an assembly that is not referenced. Consider adding a reference to assembly `System.Net.Http, Version=4.0.0.0, Culture=neutral` – Simon Jul 24 '18 at 13:37
  • @SimonHeinen what do you need HttpClient for? – Programmer Jul 24 '18 at 14:08
  • We are testing unity 2018.2 with .net 4.6 enabled and would like to use a few libraries that are using System.Net.Http. and in general it would be great to migrate away from UnityWebRequest to HttpClient if its fully supported now – Simon Jul 24 '18 at 16:01
  • 1
    @SimonHeinen I've edited my answer to include how to use `HttpClient` in the latest Unity version. Make sure to remove which ever way you were doing do it this way I mentioned. – Programmer Jul 24 '18 at 22:27
  • is there any aot/il2cpp build-related issues with system.net.http on old ios/android versions? – hiradyazdan Jul 24 '19 at 14:30
5

In the current versions of Unity httpClient is supported out of the box even on .NET Standard 2.0 targets. Here is sample code on how I use it to access a REST api.

public static async Task<Resource> GetResource()
    {
        using (var httpClient = new HttpClient())
        {
            httpClient.BaseAddress = new Uri(URL);
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var response = await httpClient.GetAsync("api/session");
            if (response.StatusCode != HttpStatusCode.OK)
                return null;
            var resourceJson = await response.Content.ReadAsStringAsync();
            return JsonUtility.FromJson<Resource>(resourceJson);
        }
    }

Copy of my answer on https://forum.unity.com/threads/httpclient-on-net-standard-2-0.608800/

noontz
  • 1,782
  • 20
  • 29