Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient not available Shared Library project Xamarin

I come to you for a common problem, but unfortunately, I was unable to find a solution.

I make a xamarin.form application, it is not a PCL, but a Shared Library project. I would like to use a REST api, and for this, I need to use a HttpClient instance. Well, here is the problem. With a PCL, I just have to add the nuget package Microsoft HTTP Client Libraries, and then I can use the HttpClient class.

With a Shared Library project, I cannot add this nuget package to the main project (which I think is normal). So I it add to to the .Droid one, and the .iOS one (oh, by the way, I am using a mac, and Xamarin Studio, if it can help). When I add the Nuget package, I can add this line : using System.Net.Http; but the class HttpClient is still unavailable. What I mean by unavailable is, I just cannot use this class (The type or namespace httpclient could not be found, are you missing an assembly reference ? )

Is there a way to use HttpClient class in a Shared Project, and not a PCL ? If yes, how ?

like image 425
QuentinRM Avatar asked Mar 27 '16 21:03

QuentinRM


1 Answers

There must have been an error while installing the Microsoft HTTP Client Libraries to your Android and iOS projects, because these project types are not supported.

Could not install package 'Microsoft.Bcl.Build 1.0.14'. You are trying to install this package into a project that targets 'MonoAndroid,Version=v6.0', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

The HttpClient comes with the Xamarin base class library https://developer.xamarin.com/api/namespace/System.Net.Http/.

So you do not need the Microsoft HTTP Client Libraries and only have to

  • reference your shared project in your Android/iOS project
  • add the Library System.Net.Http to your Android/iOS project
  • add using System.Net.Http.

On Xamarin Studio: Edit References > Packages > Check System.Net.Http

On Visual Studio: Add Reference > Assemblies > Framework > Check System.Net.Http

Protip: In addition, you could have a look at Paul Betts' ModernHttpClient: https://github.com/paulcbetts/ModernHttpClient and Kerry Lothrops blog post about HttpClientHandlers http://kerry.lothrop.de/httpclient-flavors/

like image 50
Sven-Michael Stübe Avatar answered Dec 24 '22 08:12

Sven-Michael Stübe