restclient发送json_RestSharp发送请求得到Json数据

本文介绍了一个使用RestSharp库在C#中发送POST请求并接收JSON响应的简单方法。`Post`方法设置请求参数,如Content-Type、超时和请求体,并返回服务器的响应内容。同时,`RestClientManager`类提供了更方便的接口,可以添加额外的Header,如token,并处理GET请求。
摘要由CSDN通过智能技术生成

public string Post(string url, string content)

{

string contentType = "application/json"; //Content-Type

try

{

var client = new RestClient(url);

var request = new RestRequest(Method.POST);

request.Timeout = 10000;

request.AddParameter(contentType, content, ParameterType.RequestBody);

IRestResponse response = client.Execute(request);

return response.Content; //返回的结果

}

catch (Exception ex)

{

return "连接服务器出错:\r\n" + ex.Message;

}

}

public classRestClientManager

{public JObject Post(string baseUrl, stringurl, JObject sendData)

{return Post(baseUrl, url, sendData, string.Empty);

}public JObject Post(string baseUrl, string url, JObject sendData, stringtoken)

{

RestClient client= newRestClient(baseUrl);var request = newRestRequest(url, Method.POST);var contenType = "application/json";

request.AddHeader("Accept", contenType);if (!string.IsNullOrWhiteSpace(token))

{

request.AddHeader("token", token);

}if (sendData == null)

{

sendData= newJObject();

}

request.AddParameter(contenType, sendData, ParameterType.RequestBody);var response =client.Execute(request);if (string.IsNullOrWhiteSpace(response.Content))

{return null;

}returnJObject.Parse(response.Content);

}public JObject Get(string baseUrl, stringurl, JObject sendData)

{return Get(baseUrl, url, sendData, string.Empty);

}public JObject Get(string baseUrl, string url, JObject sendData, stringtoken)

{string parames = string.Empty;if (sendData != null)

{

StringBuilder datas= newStringBuilder();foreach (var item insendData)

{

datas.AppendFormat("{0}={1}", item.Key, item.Value);

}

parames= string.Format("?{0}", string.Join("&", datas));

}var client = new RestClient(string.Format("{0}{1}{2}", baseUrl, url, parames));var request = newRestRequest(Method.GET);var response =client.Execute(request);returnJObject.Parse(response.Content);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值