在使用旧版本 RestSharp 的当前代码中,可以选择指定默认 JsonSerializer,我无法弄清楚如何在版本 107 中指定 request.JsonSerializer
var request = new RestRequest("abc");
request.AddHeader(Constants.HttpHeaderNames.ContentType, "application/json; charset=utf-8");
request.JsonSerializer = NewtonsoftJsonSerializer.Default;
Run Code Online (Sandbox Code Playgroud) 目前正在使用cloud/azure和windows phone 7进行项目,我必须打电话给服务.
对我来说,方便我休息,但我遇到了问题; 我不知道我的上诉何时完成.
public static bool CreateUser(User userToCreate)
{
if (CheckNetwork())
{
var client = new RestClient(Global.Url);
var request = new RestRequest("/user", Method.POST);
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(User));
ser.WriteObject(ms, userToCreate);
string json = JsonHelper.ToJson(userToCreate);
request.AddHeader("Content-type", "application/json; charset=utf-8");
request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
try
{
object resp = null;
client.ExecuteAsync(request, response =>
{
if (response.ResponseStatus == ResponseStatus.Completed)
{
RestResponse resource = response;
string content = resource.Content;
resp = Convert.ToBoolean(JsonHelper.FromJson<string>(content));
}
});
return …Run Code Online (Sandbox Code Playgroud) 我试图使用RestSharp读取一些json数据.
但是我在阅读json对象时遇到了一些问题.我有这个责任:
expand: "html",
self: "<url>/INCIDENT-447",
key: "INCIDENT-447",
fields: {
customfield_11414: {
name: "Corrective Measures",
type: "com.atlassian.jira.plugin.system.customfieldtypes:textarea"
},
summary: {
name: "summary",
type: "java.lang.String",
value: "BLA BLA BLA"
},
Run Code Online (Sandbox Code Playgroud)
我需要使用Property的summery和customfield_11414创建一个对象但是我只需要它们的值.不是整个JSON对象
我试图使用restsharp在单触摸项目中反序列化对象时遇到一些麻烦.
我有这个
RestResponse<List<Product>> response = client.Execute<List<Product>> (request) as RestResponse<List<Product>>;
if (response.Data != null) {}
public class Product
{
public Product () {}
[PrimaryKey]
public string Id { get; set; }
public string Name { get; set; }
[Ignore]
public string[] ParentProductIds {
get;
set;
}
Run Code Online (Sandbox Code Playgroud)
我收到了错误
找不到类型System.String []的默认构造函数.
我的json看起来像
[
{
"Id" : "62907011-02f1-440a-92ec-dc35ecf695e0",
"Name" : "ABC",
"ParentProductIds" : ["2cedbcad-576a-4044-b9c7-08872de34a96", "3fcd12ce-8117-4ae7-ae4d-f539e4268e4d"]
},
{
"Id" : "3fcd12ce-8117-4ae7-ae4d-f539e4268e4d",
"Name" : "Name 1",
"ParentProductIds" : null
}
]
Run Code Online (Sandbox Code Playgroud)
是由于null ParentProductId?
任何人都可以建议我需要做什么才能接受空数组?
在大多数情况下,我已经很快将代码从标准.NET代码移动到使用RestSharp.这对于GET进程来说已经足够简单,但我对POST进程感到难过
考虑以下
var request = System.Net.WebRequest.Create("https://mytestserver.com/api/usr") as System.Net.HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json;version=1";
request.Headers.Add("Content-Type", "application/json;version=1");
request.Headers.Add("Accepts", "application/json;version=1");
request.Headers.Add("Authorize", "key {key}");
using (var writer = new System.IO.StreamWriter(request.GetRequestStream())) {
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes("{\n \"firstName\": \"Dan\",\n \"lastName\": \"Eccles\",\n \"preferredNumber\": 1,\n \"email\" : \"testuser@example.com\",\n \"password\": \"you cant get the wood\"\n}");
request.ContentLength = byteArray.Length;
writer.Write(byteArray);
writer.Close();
}
string responseContent;
using (var response = request.GetResponse() as System.Net.HttpWebResponse) {
using (var reader = new System.IO.StreamReader(response.GetResponseStream())) {
responseContent = reader.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)
除了序列化代码之外,这是相当直接的.有什么特别的方法可以为RestSharp做这个吗?我试过创建一个对象并使用
var json = JsonConvert.SerializeObject(user);
restRequest.RequestFormat …Run Code Online (Sandbox Code Playgroud) 根据要求,我将调用REST服务,该服务将发送附件或文件作为HTTP正文中文件的二进制内容以及内容类型头的适当值,我需要打开内容在它的特定编辑器中.
我正在使用RestSharp,下面是相同的代码:例如.如果附件是.doc-
var client = new RestClient(Properties.Settings.Default.RestServicesUrl + Constants.RestTicketServices);
var restRq = new RestRequest(Constants.SearchTicket);
restRq.Method = Method.GET;
restRq.RequestFormat = DataFormat.Json;
restRq.AddParameter("account_id", "10);
client.Authenticator = new HttpBasicAuthenticator(Properties.Settings.Default.RestAuthenticationUserName, Properties.Settings.Default.RestAuthenticationPass);
IRestResponse rest = client.Execute(restRq);
Run Code Online (Sandbox Code Playgroud)
所以,在这个电话之后:
rest.ContentType ="application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset = utf-8"
rest.Content =具有word文档的二进制数据,依此类推....
基本上,我正在寻找如何读取二进制内容并在关联的编辑器中打开它.
.xls - Excel .doc - Word .pdf - Adobe等等.....
我在restsharp客户端中发现了一些性能问题,我在函数PerformanceRequest2中使用RestSharp向一些非常好的API发送请求,并在PerformRequest中使用WebRequest使用普通的.net请求
PerformRequest的平均响应时间是75毫秒,而使用RestSharp的PerformRequest2是300毫秒.这是restsharp的一些限制,还是我们使用restsharp的方式做错了
private static void PerformRequest2(string requestData)
{
var request = JsonConvert.DeserializeObject<ComplexClass>(requestData);
var client2 = new RestClient("URL");
var restRequest = new RestRequest();
restRequest.Method = Method.PUT;
restRequest.AddHeader("Content-Type", "application/json");
restRequest.AddHeader("Authorization", string.Format("Bearer {0}", token));
restRequest.AddJsonBody(request);
var restResponse2 = client2.Execute(restRequest);
if (restResponse2.StatusCode != HttpStatusCode.OK)
{
throw new Exception("error");
}
}
private static void PerformRequest(string requestData)
{
var request = JsonConvert.DeserializeObject<ComplexClass>(requestData);
var webRequest =
WebRequest.Create("URL");
webRequest.ContentType = "application/json";
webRequest.Method = "PUT";
webRequest.Headers.Add(HttpRequestHeader.Authorization, string.Format("Bearer {0}", token));
using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
{
streamWriter.Write(JsonConvert.SerializeObject(request));
streamWriter.Flush();
} …Run Code Online (Sandbox Code Playgroud) 下面是一个POST请求完成标准HttpWebRequest和HttpWebResponse.基本上它发布了带有一些参数的binanry文件.
如何使用RestSharp做同样的事情?
资源:
https://github.com/attdevsupport/ATT_APIPlatform_SampleApps/tree/master/RESTFul/SpeechCustom,ATT_APIPlatform_SampleApps/RESTFul/Speech/Csharp/app1 /]
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(string.Empty+parEndPoint );
httpRequest.Headers.Add("Authorization", "Bearer " + parAccessToken);
httpRequest.Headers.Add("X-SpeechContext", parXspeechContext);
if (!string.IsNullOrEmpty(parXArgs))
{
httpRequest.Headers.Add("X-Arg", parXArgs);
}
string contentType = this.MapContentTypeFromExtension(Path.GetExtension(parSpeechFilePath));
httpRequest.ContentLength = binaryData.Length;
httpRequest.ContentType = contentType;
httpRequest.Accept = "application/json";
httpRequest.Method = "POST";
httpRequest.KeepAlive = true;
httpRequest.SendChunked = parChunked;
postStream = httpRequest.GetRequestStream();
postStream.Write(binaryData, 0, binaryData.Length);
postStream.Close();
HttpWebResponse speechResponse = (HttpWebResponse)httpRequest.GetResponse();
Run Code Online (Sandbox Code Playgroud) 我正在使用RestSharp版本105.1.0(.NET 4.5.1)对我们自己的API进行REST调用.此API使用以下特别感兴趣的标头发送响应:Content-Type: application/json; Charset=iso-8859-1.如您所见,此响应的字符集设置为iso-8859-1.
我希望我从RestSharp得到的响应使用这种编码来解码响应内容.但是,当我查看RestResponse.Content属性时,某些字符显示为 .据我所知,这意味着使用了错误的编码.当我尝试RawBytes使用正确的编码手动解码时,我得到正确的字符串.
我尝试手动设置iso-8859-1 Encoding属性,RestClient但无济于事.
如何确保使用正确的编码解码RestSharp的响应?
示例代码:
// Setting the Encoding here does not change the result
var client = new RestClient(myApiUri) { Encoding = Encoding.GetEncoding("iso-8859-1") };
var request = new RestRequest(Method.GET);
var restResponse = client.Execute(request);
Console.WriteLine(restResponse.Content)
// Outputs content as string with wrong encoding
// some characters display as ?
Run Code Online (Sandbox Code Playgroud)
提前致谢!
如何在Visual Studio 2013中调用RestSharp?
用我的代码调用RestSharp时出错:
using System;
using System.Collections.Generic;
using System.Text;
using RestSharp; // I have an error here !
Run Code Online (Sandbox Code Playgroud) restsharp ×10
c# ×7
json ×2
.net ×1
c#-4.0 ×1
encoding ×1
rest ×1
webrequest ×1
xamarin.ios ×1