簡體   English   中英

使用 RestSharp 設置“Content-Type”標頭

[英]Set 'Content-Type' header using RestSharp

我正在為 RSS 閱讀服務構建一個客戶端。 我正在使用RestSharp庫與他們的 API 進行交互。

API 指出:

創建或更新記錄時,您必須將application/json;charset=utf-8Content-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:請使用“內容類型:應用程序/json; charset=utf-8' 標頭

為什么 RestSharp 不傳遞標題?

我博客上提供的解決方案沒有經過 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);

在 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);

老問題,但仍然是我搜索的首要問題 - 添加完整性。

雖然這有點舊:我遇到了同樣的問題..似乎某些屬性(例如“內容類型”或“日期”)不能作為參數添加,而是在內部添加。 要更改“內容類型”的值,我必須更改序列化器設置(雖然我沒有使用它,因為我在之前序列化的主體中添加了一個 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
  ...
 }

您很可能會遇到這個問題: https : //github.com/restsharp/restsharp/issues/221您的問題有一個可行的解決方案@ http://itanex.blogspot.co.at/2012/02/restsharp- and-advanced-post-requests.html

request.XmlSerializer = new DotNetXmlSerializer();
            request.Parameters.Clear();
            request.AddParameter(new Parameter()
            {
                ContentType = "application/xml",
                Name = "application/xml",
                Type = ParameterType.RequestBody,
                Value = request.XmlSerializer.Serialize(deleteUserQuery.UserDelRqHeader)
            });
            request.AddHeader("Accept", "application/xml");

這是解決方案

http://restsharp.blogspot.ca/

創建一個具有相同名稱屬性的 json 對象並設置值(確保它們與 post 請求的名稱值對相似。)

之后使用默認的httpclient。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM