我必须连接到传递Json并接收Json的服务器。使用.NET 4.5做一个简单的方法是什么?
获取令牌:(获取)
请求:
https://website.com/rest/v1/OAuth/AccessToken?client=ABCD=&password=ABC&returnFormat=json
结果:
JSON { "accessTokenResponse": { "token": "12345", "responseStatus": { "code": "100000", "message": "Service operation completed successfully", "messageDetails": "Access token assigned." } } }
调用方法:(获取)
https://website.com/rest/v1/OAuth/getEmployees?token=12345=&returnFormat=json
如何:
发送请求并使用.net接收
我尝试使用这种方法,但最推荐的是什么?
public string GetRequest(string url)
{
var request = (HttpWebRequest)WebRequest.Create(url);
try
{
var response = request.GetResponse();
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
var errorResponse = ex.Response;
using (var responseStream = errorResponse.GetResponseStream())
{
var reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
var errorText = reader.ReadToEnd();
}
throw;
}
}
答案 0 :(得分:4)
我喜欢RestSharp。您可以通过NuGet包管理器添加它。
var client = new RestClient("https://website.com");
var request = new RestRequest("/rest/v1/OAuth/AccessToken?client=ABCD=&password=ABC&returnFormat=json", Method.GET);
var response = client.Execute<Response>(request).Data;
使用json2csharp.com从您的JSON创建Response
类。这是一个在线工具。您粘贴JSON并生成C#类。
public class ResponseStatus
{
public string code { get; set; }
public string message { get; set; }
public string messageDetails { get; set; }
}
public class AccessTokenResponse
{
public string token { get; set; }
public ResponseStatus responseStatus { get; set; }
}
public class Response
{
public AccessTokenResponse accessTokenResponse { get; set; }
}