2012-11-25 62 views
5

我正在開發一個需要進行REST請求的可移植類庫,並且正在尋找諸如Restsharp或EasyHttp之類的東西。不幸的是,這些目前都不適用於PCL。或者看到一個使用基本身份驗證進行發佈請求的示例也不錯。有可用於可移植類庫的任何REST庫嗎?

如果沒有任何人有任何例子,我將如何做一個基本認證的發佈請求?

回答

1

削減PCL RestSharp的端口由於我是唯一支持的Windows Phone 7.5或更高,我能夠使用這個庫(Microsoft.Bcl.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

2

有一個剛剛發佈,目前在GitHub上可用。這就是所謂的便攜式休息

https://github.com/advancedrei/PortableRest

PortableRest是一種便攜式類庫用於其它便攜式類庫實現REST API 客戶。它利用JSON.NET的 快速,可定製的序列化,以及Microsoft.Bcl.Async 庫在任何平臺上等待執行。它被設計成 大部分與RestSharp兼容,儘管你需要 進行一些更改並重新編譯。

此初始版本對簡單JSON請求的支持有限。 更多選項(包括XML和希望DataContract支持)將在以後的版本中提供 。

相關問題