Are there any REST libraries out there that work with Portable Class Libraries? [closed]

喜夏-厌秋 提交于 2019-11-29 07:26:14

if you target 4.5 or Windows Store apps you can use HttpClient as PCL. Otherwise you can try the hack and slash PCL port of RestSharp at https://github.com/Geodan/geoserver-csharp/tree/master/RestSharp

There is one that was just recently announced and is currently available on GitHub. It's called Portable Rest

https://github.com/advancedrei/PortableRest

PortableRest is a Portable Class Library for implementing REST API clients in other Portable Class Libraries. It leverages JSON.NET for rapid, customizable serialization, as well as the Microsoft.Bcl.Async library for awaitable execution on any platform. It is designed to be largely drop-in compatible with RestSharp, though you will need to make some changes and recompile.

This initial release has limited support for simple JSON requests. More options (including XML and hopefully DataContract support) will be available in later releases.

Eric

Since I was only supporting windows phone 7.5 and higher I was able to use this library (Microsoft.Bcl.Async) to add async suppport to my plc and then use this solution.

So my code ended up looking like this:

 public async Task<RequestResult> RunRequestAsync(string requestUrl, string requestMethod, object body = null)
    {
        HttpWebRequest req = WebRequest.Create(requestUrl) as HttpWebRequest;
        req.ContentType = "application/json";

        req.Credentials = new System.Net.NetworkCredential(User, Password);

        string auth = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", User, Password)));
        var authHeader = string.Format("Basic {0}", auth);
        req.Headers["Authorization"] = authHeader;

        req.Method = requestMethod; //GET POST PUT DELETE
        req.Accept = "application/json, application/xml, text/json, text/x-json, text/javascript, text/xml";

        if (body != null)
        {
            var json = JsonConvert.SerializeObject(body, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
            byte[] formData = UTF8Encoding.UTF8.GetBytes(json);

            var requestStream = Task.Factory.FromAsync(
                req.BeginGetRequestStream,
                asyncResult => req.EndGetRequestStream(asyncResult),
                (object)null);

            var dataStream = await requestStream.ContinueWith(t => t.Result.WriteAsync(formData, 0, formData.Length));
            Task.WaitAll(dataStream);
        }

        Task<WebResponse> task = Task.Factory.FromAsync(
        req.BeginGetResponse,
        asyncResult => req.EndGetResponse(asyncResult),
        (object)null);

        return await task.ContinueWith(t =>
        {
            var httpWebResponse = t.Result as HttpWebResponse;

            return new RequestResult
            {
                Content = ReadStreamFromResponse(httpWebResponse),
                HttpStatusCode = httpWebResponse.StatusCode
            };

        });
    }

    private static string ReadStreamFromResponse(WebResponse response)
    {
        using (Stream responseStream = response.GetResponseStream())
        using (StreamReader sr = new StreamReader(responseStream))
        {
            //Need to return this response 
            string strContent = sr.ReadToEnd();
            return strContent;
        }
    }

And then I would call the code with something like:

public async Task<bool> SampleRequest()
        {            
            var res = RunRequestAsync("https//whatever.com/update/1", "PUT");
            return await res.ContinueWith(x => x.Result.HttpStatusCode == HttpStatusCode.OK);
        }

If that wasn't enough code for you feel free to check out the rest of the project here

You have a portable RestSharp working at:

https://github.com/Geodan/geoserver-csharp/tree/master/RestSharp

It seems it's working well... It uses Json.net to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!