RestSharp发送请求得到Json数据

2018/08/07 11:33
阅读数 137

NUGET安装:RestSharp

code:

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
class RestClientManager { public JObject Post(string baseUrl, string url, JObject sendData) { return Post(baseUrl, url, sendData, string.Empty); } public JObject Post(string baseUrl, string url, JObject sendData, string token) { RestClient client = new RestClient(baseUrl); var request = new RestRequest(url, Method.POST); var contenType = "application/json"; request.AddHeader("Accept", contenType); if (!string.IsNullOrWhiteSpace(token)) { request.AddHeader("token", token); } if (sendData == null) { sendData = new JObject(); } request.AddParameter(contenType, sendData, ParameterType.RequestBody); var response = client.Execute(request); if (string.IsNullOrWhiteSpace(response.Content)) { return null; } return JObject.Parse(response.Content); } public JObject Get(string baseUrl, string url, JObject sendData) { return Get(baseUrl, url, sendData, string.Empty); } public JObject Get(string baseUrl, string url, JObject sendData, string token) { string parames = string.Empty; if (sendData != null) { StringBuilder datas = new StringBuilder(); foreach (var item in sendData) { 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 = new RestRequest(Method.GET); var response = client.Execute(request); return JObject.Parse(response.Content); } }

 

使用:

       string baseUrl = "https://api.weixin.qq.com";
            string urlToken = @"/sns/oauth2/access_token";
            JObject paras = new JObject
            {
                ["appid"] = "",
                ["secret"] = "",
                ["code"] = "",
                ["grant_type"] = "authorization_code"
            };
            JObject objToken = new RestClientManager().Get(baseUrl, urlToken, paras);
       if (objToken["errcode"] == null)
            {
                string access_token = objToken["access_token"].Value<string>();
                string openid = objToken["openid"].Value<string>();
       }

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部