是否有任何REST库可以与Portable Class Libraries一起使用?

时间:2012-11-25 01:33:45

标签: c# rest portable-class-library

我正在开发一个需要发出REST请求的可移植类库,我正在寻找像Restsharp或EasyHttp这样的东西。不幸的是,这些目前都不适用于PCL。如果看到一个使用基本身份验证执行发布请求的示例,也会很高兴。

如果没有任何内容,是否有人会举例说明如何使用基本身份验证进行发布请求?

4 个答案:

答案 0 :(得分:5)

如果您定位4.5或Windows应用商店应用,则可以将HttpClient用作PCL。否则,您可以在https://github.com/Geodan/geoserver-csharp/tree/master/RestSharp

尝试破解并删除RestSharp的PCL端口

答案 1 :(得分:2)

最近刚刚宣布了一款,目前可在GitHub上使用。它被称为便携式休息

https://github.com/advancedrei/PortableRest

  

PortableRest是用于实现REST API的可移植类库   其他便携式类库中的客户端。它利用JSON.NET   快速,可自定义的序列化,以及Microsoft.Bcl.Async   在任何平台上等待执行的库。它被设计成   虽然您需要,但与RestSharp完全兼容   做一些改变并重新编译。

     

此初始版本对简单JSON请求的支持有限。   更多选项(包括XML和希望DataContract支持)将   可在以后的版本中使用。

答案 2 :(得分:1)

由于我只支持Windows Phone 7.5及更高版本,因此我可以使用此库(Microsoft.Bcl.Async)将async suppport添加到我的plc,然后使用this solution

所以我的代码最终看起来像这样:

 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;
        }
    }

然后我会用以下代码调用代码:

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

如果这个代码不够,您可以随时查看项目的其余部分here

答案 3 :(得分:0)

您有一个便携式RestSharp工作于:

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

它似乎运行良好......它使用Json.net