我在C#中有这个Windows Phone 8项目,我正在使用RestSharp 104.4.0向服务器发出请求。服务器只接受“接受”类型的“application/json”。我的代码调用请求:为什么是RestSharp AddHeader(“Accept”,“application/json”); =到项目清单?
var client = new RestClient(_jsonBaseUrl + someURL)
{
Authenticator = new HttpBasicAuthenticator(someUsername, somePassword)
};
var request = new RestRequest(Method.POST);
UTF8Encoding utf8 = new UTF8Encoding();
byte[] bytes = utf8.GetBytes(json);
json = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Accept", "application/json");
request.AddBody(json);
request.Parameters.Clear();
request.AddParameter("application/json", json, ParameterType.RequestBody);
client.ExecuteAsync<UserAccount>(request, response =>
{
if (response.ResponseStatus == ResponseStatus.Error)
{
failure(response.ErrorMessage);
}
else
{
success("done");
}
});
“json”变量是一个JSON字符串。你可以看到我的接受类型设置为AddHeader(“Accept”,“application/json”);但由于一些有线的原因,服务器接收这种接受类型: “接受”:“application/json,application/xml,text/json,text/x-json,text/javascript,text/xml”
什么我必须这样做,以确保服务器获得的唯一接受类型是“Accept”:“application/json”?
任何形式的帮助将不胜感激。
不知道为什么我找不到那与我所有的谷歌搜索:)但谢谢生病给它一个镜头。 – user2408952
它实际上是第一个结果:D –
它的工作原理,RestClient.ClearHandlers();然后RestClient.AddHandler(“application/json”,新的JsonDeserializer());然后删除request.AddHeader(“Accept”,“application/json”); – user2408952