Code Monkey home page Code Monkey logo

restsharp.portable's People

Contributors

evnik avatar fubar-coder avatar gitter-badger avatar henkmollema avatar jchannon avatar p2sh avatar rreverser avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

restsharp.portable's Issues

Could not establish trust relationship for the SSL/TLS secure channel

When attempting to hit a rest service with RestSharp.Portable I get an error related to the SSL certificate. I have been able to successfully hit other web services in the past using this library.

It looks like the common answer has been to use ServicePointManager to validate the certificates yourself but that API doesn't appear to be available in a profile 78 PCL. Is there anything that RestSharp.Portable exposes to allow filtering/validating certificates?

System.AggregateException: One or more errors occurred. ---> System.Net.Http.HttpRequestException: A
n error occurred while sending the request. ---> System.Net.WebException: The underlying connection
was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Secur
ity.Authentication.AuthenticationException: The remote certificate is invalid according to the valid
ation procedure.
   at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
   at System.Net.PooledStream.EndWrite(IAsyncResult asyncResult)
   at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at RestSharp.Portable.RestClient.<ExecuteRequest>d__33.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at RestSharp.Portable.RestClient.<Execute>d__8`1.MoveNext()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at EulaWebServiceTest.Program.Main(String[] args) in c:\Users\afishe\Desktop\EulaWebServiceTest\P
rogram.cs:line 26
---> (Inner Exception #0) System.Net.Http.HttpRequestException: An error occurred while sending the
request. ---> System.Net.WebException: The underlying connection was closed: Could not establish tru
st relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationEx
ception: The remote certificate is invalid according to the validation procedure.
   at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
   at System.Net.PooledStream.EndWrite(IAsyncResult asyncResult)
   at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at RestSharp.Portable.RestClient.<ExecuteRequest>d__33.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at RestSharp.Portable.RestClient.<Execute>d__8`1.MoveNext()<---

Execute method stuck in deadlock when called twice in a raw

I've a 100% reproduce when client.Execute stuck in a deadlock if the method called twice in a raw.

Code example (this is not a working code, just an example of reproduce):

var t1 = client.Execute (request1);
var t2 = client.Execute (request2);
await Task.WaitAll (t1, t2);
// this point never reached

The reason: RequestGuard lock in a synchronous ways.

Using AsyncLock solves the problem. Examples of AsyncLock implementation could be found:
http://www.hanselman.com/blog/ComparingTwoTechniquesInNETAsynchronousCoordinationPrimitives.aspx and here
http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266988.aspx

NullReferenceException with AddBody method

good day!
i try to use your library but have confused when need send json request to server:

var request = new RestRequest("/api/some_method", HttpMethod.Post);
request.AddBody(new MethodRequest
    {
        Parameter = "Parameter",
    });

var response = _client.Execute<MethodResponse>(request);
in runtime i have exception:
Object reference not set to an instance of an object. at
   at Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at Microsoft.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccess(Task task)
   at Microsoft.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at Microsoft.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at RestSharp.Portable.RestClient.<Execute>d__7`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at App1.MainPage.<ButtonBase_OnClick>d__0.MoveNext()

other method (without request body) work fine
then i try to set up body with AddParameter:

request.AddParameter("text/html", new MethodRequest
    {
        Parameter= "Parameter",
    }, ParameterType.RequestBody);

and this work perfectly

Restsharp Crashing WP app by throwing an exception that is not propagated to caller

I have been receiving crashes due to RestSharp throwing an exception that can't be caught by me (some internal task barfing up?). I receive following Stack-trace whenever this happens.

System.AggregateException: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread.
  at unknown location

Aggregated Exception [0]: System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at Microsoft.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccess(Task task)
   at Microsoft.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at RestSharp.Portable.RestClient.<Execute>d__10.MoveNext()

my code is pretty simple

try {
  await restSharpClient.Execute(request, cancellationToken);
} catch(Exception e) {
  // Exception should be caught here
}

Where cancellationToken is always CancellationToken.None, sending in a Token that is cancelled externally increases the number of crashes. Am I doing something wrong? Is there any flag? I have already set IgnoreResponseStatusCode flag to true already. There is a timeout of 60 seconds.

Usage of ModernHttpClient

Hi !

I'm relatively new to C# development and I don't know if my issue is relevant but as I also have a few remarks/questions, I wanted to ask :

  • Would it not be worth using https://github.com/paulcbetts/ModernHttpClient internally ?
  • It's not possible to use (error 404) your RestClient with a BaseUrl that doesn't have a trailing "/" (the Resource from RestRequest starts directly with "/").
  • I use this PCL with Xamarin and I noticed one strange inconvenience due to the Microsoft.Bcl.Build package dependency : I'm not able to use typeof(MyClass).GetTypeInfo().Assembly anymore ... Do you have any idea to get around this problem ?

Thx in advance for your help ! =)

Getting content when there's an exception

For validation, etc. scenarios, it's useful to be able to access the response content in case of failure. I can see that the following is used:

 if (!this.IgnoreResponseStatusCode)
              response.EnsureSuccessStatusCode();

And that we can set Ignore... to false to get the IRestResponse with raw bytes, status code, etc. However, it's a bit tedious to then check whether it's successful or not. Specially since HttpClient provides am IsSuccessStatus helper. I think it would be useful to have this available in the response. I can think of three ways that may deal with this scenario (i.e. get content in case of failure):

  1. Add a boolean to IRestResponse that basically takes the value of httpclient's IsSuccess flag.
  2. Add an EnsureSuccessCode method on IRestResponse that throws an exception that has the RestResponse contents inside of it.
  3. Instead of bubbling HttpClient's exception raised in Ensure..(), trap it and throw a different exception that has the payload, etc. in it. Guessing this would be a breaking change.

Having easy access to the content would allow clients to use validation messages, etc. without forcing them to do weird Message parsing (if errors aren't ignored), and without having to do validation around the IRestResponse status code (in case of ignoring errors).

Thoughts?

Does FubarCoder.RestSharp.Portable.OAuth package can be installed in Windows 10 UAP Class Library?

I'm trying to install FubarCoder.RestSharp.Portable.OAuth to use OAuth1Authenticator class in my application Class Library (Windows Universal). But package manager console indicate an error such as:

PM> Install-Package FubarCoder.RestSharp.Portable.OAuth
Attempting to gather dependencies information for package 'FubarCoder.RestSharp.Portable.OAuth.2.4.3' with respect to project targeting 'Windows, Version=v8.1'
Attempting to resolve dependencies for package 'FubarCoder.RestSharp.Portable.OAuth.2.4.3' with DependencyBehavior 'Lowest'
Install-Package : Unable to satisfy package dependency constraints.
At line:1 char:1

  • Install-Package FubarCoder.RestSharp.Portable.OAuth
  • - CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
    - FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand
    
    

Is the a chance to FubarCoder.RestSharp.Portable.OAuth package will support and can be installed under Class Library (Windows Universal) project type?

P.S.
I've successfully installed FubarCoder.RestSharp.Portable -Version 2.4.3 into my Windows10 project - BlankApp (Windows Universal).

Nested object are always null

Hello,
First thanks a lot for your great work... :-)
I've a big issue with nested object on PUT/POST calls.
My object definition:

public class ObjectA 
{
    public string Name {get; set;}
    public ObjectB MyObjectB {get; set;}
}

public class ObjectB 
{
    public string Description {get; set;}
}

Now I'm trying to POST a new object to my REST API with the code bellow:

var myObjectA = new ObjectA
{
    Name = "My Object A",
    MyObjectB = new ObjectB 
    {
        Description = "My nested ObjectB"
    }
};

var resClient = new RestClient
{
    BaseUrl = new System.Uri("http://mybaseurl/"),
    TimeOut = 30
};
var restRequest = new RestRequest("ObjectsA", HttpMethod.Post);
resRequest.AddObject(myObjectA);
var restResponse = await restClient.Execute<ObjectA>(restRequest);

Now my REST API looks like this:

 [System.Web.Http.HttpPost]
 [System.Web.Http.AcceptVerbs("POST")]
 [ResponseType(typeof(ObjectA))]
public async Task<IHttpActionResult> PostObjectAAsync(
            [FromBody]ObjectA myNewObjectA)
{
    try
        {
              // check if the parameter are deserialized
              if (!ModelState.IsValid)
          {
                    return BadRequest(ModelState);
           }
....
}

My problem is my myNewObjectA.MyObjectB property is always null and it's the same for all the object properties...other scalar type properties are correct.

Thanks for your support !!!
Kind regards,
Florian

FileParameter

Sended files parameters are loaded to memory instead of using StreamContent. Can cause OutOfMemoryExceptions.

RestResponse on Bad Request

Maybe I am doing something wrong, but everytime server returns Bad Reqest (400), Conflict (409), etc. HttpRequestException occurs... I thought it should be processed inside RestSharp.Portable and returned as StatusCode in RestResponse.
I am using version 3.0.0 alpha 4

Response HTTP status

Hello,
there's a problem for me getting the HTTP Response in case of failure, I need to differentiate handling based on the returned status.
This is how I'm calling the service:

            RestClient _client = new RestClient(new Uri(API_URL));
            _client.HttpClientFactory = new CustomHttpClientFactory();
            var request = new RestRequest(HttpMethod.Get);
            request.Resource = PATH_HEADER + "branches/{branchPublicId}/services/{servicePublicId}/dates";
            request.AddParameter("branchPublicId", branchPublicId, ParameterType.UrlSegment);
            request.AddParameter("servicePublicId", servicePublicId, ParameterType.UrlSegment);
            var execTask = _client.Execute<T>(request);
            execTask
              .ContinueWith(t =>
              {
                   var result = t.Result;
                   if (result.Data == null)
                       callback.Failure(new NullReferenceException(), "Result data is null");
                   else
                       callback.Success((T)result.Data);
              }, TaskContinuationOptions.OnlyOnRanToCompletion);
            execTask
              .ContinueWith(t =>
              {
                  var exception = t.Exception;
                  callback.Failure(exception, exception.Message);
              }, TaskContinuationOptions.OnlyOnFaulted);

Is there something I'm missing, because I cannot parse "t" into RestResponse, just IRestResponse, in which I cannot get the HTTP response status.

Thank you

Execute<T>(Request)

I'm trying Restsharp.portable library in xamarin,
When I try to execute my Request it's seems dead, When the application call client.Execute method it freezing without launch any exception!!

var client = new RestClient();
client.BaseUrl = new Uri(this.BaseUrl);
client.ClearHandlers();
Request.AddHeader("Authorization", "Basic " + credentials);
var response = await client.Execute(Request);

If I try to send request from unitTest it works, but when I try to send form xamarin application no!
Why?

Thanks
Mattia

Must append BaseUrl

Not sure what I am missing here, but the client is forcing me to append the BaseUri to my resource URLs, or else I always get a 404. This is contrary to the example code, and the exact same implementation works when I substitute RestSharp.Portable for RestSharp.

public class MyService
{
    private readonly RestClient _client;

    public MyService()
    {
        _client = new RestClient("https://api.mywebsite.com/1");
    }

    public async Task<IList<Event>> GetEventsAsync()
    {
        // why do i need to append the base url?
        var request = new RestRequest(_client.BaseUrl + "/events?api_key={api_key}&query={query}", HttpMethod.Get);

        request.AddUrlSegment("api_key", "api_key_here");
        request.AddUrlSegment("query", "dodgers");

        var response = await _client.Execute<ApiResponse<Event>>(request);

        if (response.Data == null)
        {
            throw new Exception(":(");
        }

        return response.Data.Results;
    }
}

HttpRequestException 500 (Internal Server Error) - Hangs in iOS POST Request

I am trying to POST data using a Xamarin iOS unit test project and I can successfully make GET requests but when I try to do a POST it always fails. My web service also has Swagger documentation and I was able to POST data using that but never with this library. Is this a good example of how to call it for a POST request?

When the client.Execute() method is invoked, it returns the error below. I also verified no network traffic occurs from the mobile client when proxy through Fiddler.

var payload = new User()
{
    FirstName ="Suzy",
    LastName = "Q",
    Age = 43
};

using (var client = new RestClient("http://mywebservice.com:8308"))
{
    var request = new RestRequest("api/Accounts/Register", HttpMethod.Post);
    request.AddJsonBody (payload);
    var result = await client.Execute<UserRegistrationResponse>(request);
    var userId = result.Data.UserId;
}

ios simulator screen shot jun 1 2015 10 46 06 am

HttpBasicAuthenticator does not support pre-authenticate

HttpBasicAuthenticator fills token after challenge handling only. However, my server does not return appropriate WWW-Authenticate header.

I added following constructor for myself:

        public HttpBasicAuthenticator(string username, string password)
        {
            _authToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"));
        }

Similar constructor presents in RestSharp: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Authenticators/HttpBasicAuthenticator.cs

Absolute URI for a RestRequest only keeps the path and query

The following test case fails:

using (var client = new RestSharp.Portable.WebRequest.RestClient("https://www.itsg-trust.de/ostc/")
{
    HttpClientFactory = CreateClientFactory(typeof(WebRequestHttpClientFactory), false),
})
{
    var request = new RestRequest(new Uri("http://www.itsg.de/tc_keys_arbeitgeberverfahren.ITSG"));
    var targetUri = client.BuildUri(request);
    Assert.Equal(new Uri("http://www.itsg.de/tc_keys_arbeitgeberverfahren.ITSG"), targetUri);
}

Creating a response object in case of exception

Apologies for duplicate post, I posted the same question on your reddit before
https://www.reddit.com/r/FubarDev/comments/3cagk7/creating_a_response_object_to_handle_exceptions/

When using the full restSarp library we use the following code snippet to create a response object in case of an exception occurs.

try
            {
 response = await client.ExecuteTaskAsync<T>(request, new CancellationTokenSource(30000).Token);
            }
catch (Exception exception)
         {
            response = new RestResponse<T>
                { 
                    ResponseStatus = exception is TaskCanceledException ? ResponseStatus.TimedOut     :ResponseStatus.Error,
                ErrorException = exception
            };
        } 

Since ResponseStatus & ErrorException are not available in this version of port, what are my options to create a response object in case of an exception?
Thanks

Url segments in query string parameters don't work for first parameter

Consider the following url:

/api/foo?x={x}&y={y}&z={z}

When adding url segments x, y and z, it seems RestSharp.Portable creates the following url after expansion:

/api/foo??x={x}&y={y}&z={z}

Note the extra question mark. On the server (at least in web api), the first parameter as seen as "?x" instead of x, and as such doesn't bind x.

The following url template works:

/api/foo?&x={x}&y={y}&z={z}

which expands to

/api/foo??&x={x}&y={y}&z={z}

This works as it thinks x is the second parameter, and binds correctly. However that's still a bit ugly.

I checked in RestSharp (i.e. not portable) and it doesn't create the double ? problem. Wondering if this is a difficult fix.

Add a HAL deserializer

Hi!

Firstly thanks for your work on the library! It's been a great help so far, however one thing I'd love to have in it is missing - a HAL deserializer. One that would support the _links and _embedded properties. I am currently working on a project consuming an API that spits out HAL and I'm having difficulties building models with nested entries.

I thrawled the net trying to either find a library that would do it for me or a standalone deserializer but with no luck and thought it would be awesome if there was one shipped with Restsharp Portable.

Obviously feel free to close this "issue" but I would appreciate any kind of answer from you, even if it's a no.

Thanks!

request.AddHeader("Content-Type") - It does not work

hello i'm try to execute this code on xamarin forms:

..
var client = new RestClient("http://192.168.1.100/TestWebAPI/");
var request = new RestRequest("Token", Method.POST);
request.AddParameter("username","[email protected]");
request.AddParameter("password","123456");
request.AddParameter("grant_type","password");
request.AddHeader("content-type", "application/x-www-form-urlencoded;charset=utf-8");
IRestResponse t = client.Execute(request).Result;
...

but the code go exception and show me this error:
in Exception.Message.Tostring() show this "One or more errors occurred."

in innerexeption show this

{System.InvalidOperationException: content-type at System.Net.Http.Headers.HttpHeaders.CheckName (System.String name) [0x0005f] in /Users/builder/data/lanes/1503/6481535e/source/mono/mcs/class/System.Net.Http/System.Net.Http.Headers/HttpHeaders.cs:253 at System.Net.Http.Headers.HttpHeaders.Contains (System.String name) [0x00000] in /Users/builder/data/lanes/1503/6481535e/source/mono/mcs/class/System.Net.Http/System.Net.Http.Headers/HttpHeaders.cs:285 at RestSharp.Portable.HttpClientImpl.DefaultHttpClientFactory.AddHttpHeaderParameters (System.Net.Http.HttpRequestMessage message, IRestRequest request) [0x00043] in :0 at RestSharp.Portable.HttpClientImpl.DefaultHttpClientFactory.CreateRequestMessage (IRestClient client, IRestRequest request) [0x0001a] in :0 at RestSharp.Portable.RestClient+d__31.MoveNext () [0x000e6] in :0 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000b] in /Users/builder/data/lanes/1503/6481535e/source/mono/mcs/class/corlib/System.Runtime.ExceptionServices/ExceptionDispatchInfo.cs:61 at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/1503/6481535e/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:201 at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/1503/6481535e/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:170 at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/1503/6481535e/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:142 at System.Runtime.CompilerServices.TaskAwaiter`1[System.Net.Http.HttpResponseMessage].GetResult () [0x00000] in /Users/builder/data/lanes/1503/6481535e/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:372 at RestSharp.Portable.RestClient+d__0.MoveNext () [0x0011e] in :0 } System.InvalidOperationException

How can i resolve it ?

Thanks
alex

IgnoreResponseStatusCode property does not work on UWP apps?

Hi,

I am currently using RestSharp.Portable for a while now and I used to set the IgnoreResponseStatusCode of the RestClient class to true in order to manage errors (especially connectivity errors) by myself.

Here a very simple example in a Windows Phone 8.1 app using the universal project and the RestSharp.Portable.HttpClient in version 3.1.0 :

try
{
    var client = new RestClient("http://www.google.fr") { IgnoreResponseStatusCode = false };
    var request = new RestRequest() {Method = Method.GET };
    var data = await client.Execute(request);

    Debug.WriteLine(data.IsSuccess == true ? "success" : "failed");
}
catch (Exception exception)
{
    Debug.WriteLine(exception.Message);
}

If I do not have an internet connection, the code throws a System.Net.Http.HttpRequestException exception with the message Response status code does not indicate success: 404 (Not Found)..

And now, if I set the IgnoreResponseStatusCode property to true, the code does not throw any exception. This is the behavior expected, I mean the behavior I have since I use this library.

The issue appears when I am trying to execute the same code on a UWP app with the same version of the RestSharp.Portable.HttpClient library.

It seems that the IgnoreResponseStatusCode does not work and, if I do not have an internet connection, the code throws the following exception (no matter the value is set to true or false) : System.Net.Http.HttpRequestException with the message An error occurred while sending the request.

Is there a way to do not throw an exception in this case ? Is this an issue into the RestSharp.Portable.HttpClient library or is this a normal behavior of the UWP ?

Thx for your help.

Edit : If I use RestSharp.Portable.WebRequest instead of RestSharp.Portable.HttpClient it seems to work correctly

Creating and disposing http clients on each request?

Is seems the RestClient class is creating and disposing http clients for each request. This seems to be a bad practice: http://stackoverflow.com/questions/18976042/httpclientfactory-create-vs-new-httpclient . When integrating with other clients that expect long lived instances, this is causing us some problems. Is this by design? Is there a workaround? Maintaining a singleton in a custom factory doesn't work either as clients are expected to get created with a request message:

var httpClient = HttpClientFactory.CreateClient(this, request)

Use ModernHttpClient Instead of DefaultHttpClientFactory

Is there an easy way to replace the HttpClientFactory on the client so it uses ModernHttpClient's NativeMessageHandler?

This is my initial stab at integrating it but I didn't see a way to set the _proxyProperty from the DefaultHttpClientFactory the same way it did.

/// <summary>
    /// An HTTP Client Factory that uses the high-performance ModernHttpClient's NativeMessageHandler to process requests.
    /// </summary>
    public class ModernHttpClientFactory : DefaultHttpClientFactory
    {
        #region Methods

        /// <summary>
        /// Create the message handler.
        /// </summary>
        /// <param name="client">The REST client that wants to create the HTTP client</param>
        /// <param name="request">The REST request for which the HTTP client is created</param>
        /// <returns>
        /// A new HttpMessageHandler object
        /// </returns>
        protected override HttpMessageHandler CreateMessageHandler(IRestClient client, IRestRequest request)
        {
            var proxy = GetProxy(client);
            var cookies = GetCookies(client, request);
            var credentials = client.Credentials;
            var httpClientHandler = new NativeMessageHandler();

            if (httpClientHandler.SupportsProxy && proxy != null)
            {
                httpClientHandler.UseProxy = true;
                httpClientHandler.Proxy = new RequestProxyWrapper(proxy); ;
            }

            if (cookies != null)
            {
                httpClientHandler.UseCookies = true;
                httpClientHandler.CookieContainer = cookies;
            }

            if (credentials != null)
            {
                httpClientHandler.Credentials = credentials;
            }

            return httpClientHandler;
        }

        #endregion
    }

No way to set AccessToken in OAuth2Client from outside

There is need to restore AccessToken from own vault instead of forcing user to reauthenticate every time app is started, but AccessToken currently has private set mode and no method allows to set it initially to own value.

System.Threading.Tasks.TaskCanceledException: A task was canceled.

The following code throws exception with message:
Caused by: md52ce486a14f4bcd95899665e9d932190b.JavaProxyThrowable: System.Threading.Tasks.TaskCanceledException: A task was canceled.

    protected override async void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        if (!IsConnectedToService())
        {
            throw new Exception("cant connect to service");
        }

        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        ListView carListView = FindViewById<ListView>(Resource.Id.carlistView);

        List<string> cars = (await _client.GetAllAsync()).Select(x=>x.Model).ToList();

        _adapter = new ArrayAdapter(
            this,
            Android.Resource.Layout.SimpleListItem1,
            cars);

        carListView.Adapter = _adapter;
    }

    public async Task<List<T>> GetAllAsync()
    {
        RestRequest request = new RestRequest();

        var response = await _restClient.Execute<List<T>>(request);

        return response.Data;
    }

This is full stack trace:

11-11 13:16:03.774 E/AndroidRuntime(  966): FATAL EXCEPTION: main
11-11 13:16:03.774 E/AndroidRuntime(  966): Process: AndroidConsumer.AndroidConsumer, PID: 966
11-11 13:16:03.774 E/AndroidRuntime(  966): java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
11-11 13:16:03.774 E/AndroidRuntime(  966):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
11-11 13:16:03.774 E/AndroidRuntime(  966): Caused by: java.lang.reflect.InvocationTargetException
11-11 13:16:03.774 E/AndroidRuntime(  966):     at java.lang.reflect.Method.invoke(Native Method)
11-11 13:16:03.774 E/AndroidRuntime(  966):     at java.lang.reflect.Method.invoke(Method.java:372)
11-11 13:16:03.774 E/AndroidRuntime(  966):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
11-11 13:16:03.774 E/AndroidRuntime(  966):     ... 1 more
11-11 13:16:03.774 E/AndroidRuntime(  966): Caused by: md52ce486a14f4bcd95899665e9d932190b.JavaProxyThrowable: System.Threading.Tasks.TaskCanceledException: A task was canceled.
11-11 13:16:03.774 E/AndroidRuntime(  966): at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000b] in /Users/builder/data/lanes/2058/96592261/source/mono/mcs/class/corlib/System.Runtime.ExceptionServices/ExceptionDispatchInfo.cs:61
11-11 13:16:03.774 E/AndroidRuntime(  966): at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>m__0 (object) [0x00000] in /Users/builder/data/lanes/2058/96592261/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1006
11-11 13:16:03.774 E/AndroidRuntime(  966): at Android.App.SyncContext/<Post>c__AnonStorey0.<>m__0 () [0x00000] in /Users/builder/data/lanes/2058/96592261/source/monodroid/src/Mono.Android/src/Android.App/SyncContext.cs:18
11-11 13:16:03.774 E/AndroidRuntime(  966): at Java.Lang.Thread/RunnableImplementor.Run () [0x0000b] in /Users/builder/data/lanes/2058/96592261/source/monodroid/src/Mono.Android/src/Java.Lang/Thread.cs:36
11-11 13:16:03.774 E/AndroidRuntime(  966): at Java.Lang.IRunnableInvoker.n_Run (intptr,intptr) [0x00009] in /Users/builder/data/lanes/2058/96592261/source/monodroid/src/Mono.Android/platforms/android-21/src/generated/Java.Lang.IRunnable.cs:71
11-11 13:16:03.774 E/AndroidRuntime(  966): at (wrapper dynamic-method) object.a29135ab-f122-4aad-a167-ff222dc57614 (intptr,intptr) <IL 0x00011, 0x0001f>
11-11 13:16:03.774 E/AndroidRuntime(  966): 
11-11 13:16:03.774 E/AndroidRuntime(  966):     at mono.java.lang.RunnableImplementor.n_run(Native Method)
11-11 13:16:03.774 E/AndroidRuntime(  966):     at mono.java.lang.RunnableImplementor.run(RunnableImplementor.java:29)
11-11 13:16:03.774 E/AndroidRuntime(  966):     at android.os.Handler.handleCallback(Handler.java:739)
11-11 13:16:03.774 E/AndroidRuntime(  966):     at android.os.Handler.dispatchMessage(Handler.java:95)
11-11 13:16:03.774 E/AndroidRuntime(  966):     at android.os.Looper.loop(Looper.java:135)
11-11 13:16:03.774 E/AndroidRuntime(  966):     at android.app.ActivityThread.main(ActivityThread.java:5253)
11-11 13:16:03.774 E/AndroidRuntime(  966):     ... 4 more
11-11 13:21:03.825 I/Process (  966): Sending signal. PID: 966 SIG: 9

Implement RestSharps DeserializeAs attribute

DeserializeAs allows a different name for the property in the serialized XML/JSON file.

This feature cannot be implemented for XML due to the restrictions of the DataContractSerializer. There might be a way for JSON, but I doubt that it's worth the effort.

OAuth 1.0 and OAuth1Authenticator custom Timestamp

When we try to authenticate to some service with help of OAuth1Authenticator, the Autorization header will be generated automatically. It will looks like
"OAuth oauth_version="1.0", oauth_signature_method="HMAC-SHA1", oauth_nonce="8335006", oauth_timestamp="1414663625", oauth_consumer_key="9612eaca23c7bdd3eca60dc8c2a8159c", oauth_signature="M6sLyyfHGYXOtQnLJexDx96kbFo=", oauth_token="8d0e43fd0cc67726567d49ae5e818852"";

And, for instance, I want to set custom time stamp, using server time for example, not client one. It is no way to set a custom "oauth_timestamp" during generation of Autorization header with help of OAuth1Authenticator. What if "OAuth1Authenticator" will have a property or method that allows developer to set the time stamp?

some code:
var restClient = new RestClient(_serviceUrl);
var request = new RestRequest(RequestTokenRequest, Method.POST);
restClient.Authenticator = OAuth1Authenticator.ForRequestToken(_consumerKey, _consumerSecret);
((OAuth1Authenticator)restClient.Authenticator).SignatureMethod = OAuthSignatureMethod.PlainText;

// is it make sense?
((OAuth1Authenticator)restClient.Authenticator).TimeStamp = _customTimeStamp;

OAuth, OAuth2 multiple definitions in Android projects

If you add RestSharp.Portable.OAuth2 as NuGet package to your Xamarin Android app, you get
"The type 'RestSharp.Portable.Authenticators.Resource' exists in both..." error messages because ApplicationName and Hello string resources defined in both RestSharp.Portable.OAuth and RestSharp.Portable.OAuth2 assembly.

System.UriFormatException: Uri is longer than the maximum 32766 characters

Hi !

First, thank you for keeping this library up-to-date ! ;)

My problem is that I have a WebService that requires to send image as base64 string and obviously, sometimes it is longer than this character limit on Uri when "EscapeDataString" method is called (as < 4.5 .NET but the new limit for 4.5 .NET is in excess of 65,500 characters btw). ;)

Could you merge this issue restsharp/RestSharp@54a4d15 to resolve it ? And be sure to use "UrlEncode" method over "EscapeDataString" directly ?

I'd love to help but I'm not sure what changes to make ... Maybe you can indicate me and I'll do the rest with a pull request ? =)

Thx !

Problem with using in iOS Unified project

After added Nuget package to an iOS Unified class library, I receive:
Error CS0012: The type System.Object' is defined in an assembly that is not referenced. Consider adding a reference to assembly System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' (CS0012)
This occurs when for example defining a class inherited from JsonConverter.
In iOS Classic class library it works fine.

Timeout not working on Android (Xamarin)

Hey fubar-coder,

Seems that the Timeout property on IRestClient doesn't work on Android. :/

  var source = new CancellationTokenSource();
  source.CancelAfter(TimeSpan.FromSeconds(10));

  using (IRestClient client = new RestClient("http://www.somerandomserverurl.com"))
  {
    client.Timeout = TimeSpan.FromSeconds(10);

    var request = new RestRequest("Request", HttpMethod.Get);
    try
    {
      return await client.Execute(request, source.Token);
    }
    catch (Exception ex)
    {
      throw;
    }
  }

It would also appear that the CancellationToken doesn't work, I find myself waiting the 100+ seconds for the HttpClient to timeout which is rather painful (not the expected System.AggregateException/TaskCanceledException).

Perhaps I'm doing something incorrectly, your help would be greatly appreciated.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.