2015-09-04 104 views
0

我遇到問題,並認爲我可能會錯過某些與RestSharp。 我正在授權並取回一個cookie就好了......看下面。但是當我打電話來獲取數據時,它會返回未授權的狀態。它在Postman中工作得很好,但不在下面的代碼中。我正在使用控制檯應用程序,並嘗試通過AddHeader,AddCookie發送cookie,並將其作爲參數。 responseLogin包含正確的cookie。任何幫助都會很棒。RestSharp返回未授權

Dim clientLogin = New RestClient("http://[URI to Authorize]............") 
    Dim requestLogin = New RestRequest(Method.POST) 

    requestLogin.AddParameter("application/x-www-form-urlencoded", "[Username and password here.....]", ParameterType.RequestBody) 
    Dim responseLogin As IRestResponse = clientLogin.Execute(requestLogin) 




    Dim client = New RestClient("http://[URI to get data]............") 
    Dim request = New RestRequest(Method.GET) 

    request.AddHeader("Cookie", responseLogin.Cookies(0).Value.ToString) 
    request.AddHeader("Accept", "application/json") 

    Dim response As IRestResponse = client.Execute(request) 

回答

0

Cookie標頭需要包含cookie的名稱和值,例如,

Dim authCookie = responseLogin.Cookies(0) ' Probably should find by name 
request.AddHeader("Cookie", String.Format("{0}={1}", authCookie.Name, authCookie.Value)) 

然而,the documentation(我從來沒有用過RestSharp個人)說,RestSharp有餅乾自動支持,所以如果你重用RestClient實例並設置CookieContainer你不需要做任何事情來處理手動(除非你想要,在某些情況下可能會更好)。

Dim client = New RestClient(New Uri("[Base URI...]")) 
client.CookieContainer = New System.Net.CookieContainer() 

Dim requestLogin = New RestRequest("[login page path]", Method.POST) 
requestLogin.AddParameter("application/x-www-form-urlencoded", "[Username and password here.....]", ParameterType.RequestBody) 
Dim responseLogin As IRestResponse = client.Execute(requestLogin) 

Dim request = New RestRequest("[data api path", Method.GET) 
request.AddHeader("Accept", "application/json") 
Dim response As IRestResponse = client.Execute(request) 

你很可能只是重複使用不同RestClient實例,而不是重用client cookie的容器。