2013-07-23 31 views
24

我正在爲RSS閱讀服務構建客戶端。我正在使用RestSharp庫與其API進行交互。使用RestSharp設置'Content-Type'標題

的API狀態:

當創建或更新您必須設置應用程序/ JSON的記錄; charset = utf-8作爲Content-Type標頭。

這是我的代碼如下所示:

RestRequest request = new RestRequest("/v2/starred_entries.json", Method.POST); 
request.AddHeader("Content-Type", "application/json; charset=utf-8"); 
request.RequestFormat = DataFormat.Json; 
request.AddParameter("starred_entries", id); 

//Pass the request to the RestSharp client 
Messagebox.Show(rest.ExecuteAsPost(request, "POST").Content); 

然而,該服務正在返回「錯誤415:請使用'Content-Type:application/json; charset = utf-8'標題。」爲什麼RestSharp不通過標題?

+0

我對RestSharp不熟悉,但我會使用Fiddler檢查請求以確定RestSharp IS傳遞的是什麼。可能是Content-Type頭已經被添加了,你需要替換或刪除/添加它。 我會假設'request.RequestFormat = DataFormat.Json'爲你設置Content-Type標題。 –

+0

我試過了,沒有這條線。唯一的選擇是JSON或XML。 –

+0

請發佈請求在Fiddler中的外觀,它會告訴我們是否添加了Content-Type,而不是僅僅猜測。 – Darius

回答

37

提供my blog該解決方案超越RestSharp的1.02版本沒有進行測試。如果您就我的解決方案的具體問題提交了有關我的答案的評論,我可以對其進行更新。

var client = new RestClient("http://www.example.com/where/else?key=value"); 
var request = new RestRequest(); 

request.Method = Method.POST; 
request.AddHeader("Accept", "application/json"); 
request.Parameters.Clear(); 
request.AddParameter("application/json", strJSONContent, ParameterType.RequestBody); 

var response = client.Execute(request); 
+2

在我的具體情況中,'strJSONContent'變量應該包含什麼內容? –

+1

strJSONContent是表示要在POST請求期間發送的數據的JSON字符串。這必須是有效的JSON,以便服務器可以正確解釋它。 使用RestSharp並檢查包含JSON字符串的參數時,結果將包含mimetype和數據,如下所示: 「application/json = {\」key1 \「:\」value1 \「,\」 key2 \「:\」value2 \「}」 – itanex

+0

這對你有所幫助@ShaneGowland – itanex

-3

下面是解

http://restsharp.blogspot.ca/

創建具有相同名稱的屬性JSON對象和設置的值(確保它們類似於那些名稱值對POST請求的。)

之後,使用默認httpclient。

8

雖然這是有點舊:我遇到了同樣的問題..似乎有些屬性,如「內容類型」或「日期」不能作爲參數添加,但在內部添加。要改變的「內涵式」的值,我不得不盡快改變serialzer設置(altough我didn`t使用它,因爲我加在體內的JSON那是以前連載!)

RestClient client = new RestClient(requURI); 
RestRequest request = new RestRequest(reqPath, method); 
request.JsonSerializer.ContentType = "application/json; charset=utf-8"; 

我沒這個標題出現了像預期一樣:

System.Net Information: 0 : [5620] ConnectStream#61150033 - Header 
{ 
    Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml 
    User-Agent: RestSharp 104.1.0.0 
    Content-Type: application/json; charset=utf-8 
    ... 
} 
17

在版本105.2.3.0我可以解決的問題是這樣的:我的搜索

var client = new RestClient("https://www.example.com"); 
var request = new RestRequest("api/v1/records", Method.POST); 
request.AddJsonBody(new { id = 1, name = "record 1" }); 
var response = client.Execute(request); 

老問題,但還是頂 - 添加的完整性。

+0

這是當前版本的restsharp 105.2.3最優雅的解決方案 – BrokeMyLegBiking