1.获取 Token
string url = "http://10.168.9.21/api/services/Org/UserLogin";
var para = new
{
UserName = "admin",
Password = "edoc2"
};
var result_NewIncident = HttpUtility.HttpPostJson(url, para);
JObject obj = JObject.Parse(result_NewIncident);
string token = obj.GetValue("data").ToString();
附件是 请求通用类 Post Get 通过 webclient
/// <summary>
/// HttpUtility
/// </summary>
public class HttpUtility
{
/// <summary>
/// HttpClient
/// </summary>
private static HttpClient client = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip });
/// <summary>
/// Content-Type:application/json
/// </summary>
/// <param name="apiUrl"></param>
/// <param name="data"></param>
/// <returns></returns>
public static string HttpPostJson(string apiUrl, Object data)
{
string result = string.Empty;
//client.DefaultRequestHeaders.Add("Authorization", $"{Token.type} {Token.access_token}");
var postData = JsonConvert.SerializeObject(data);
var httpContent = new StringContent(postData, Encoding.UTF8);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = client.PostAsync(apiUrl, httpContent);
response.Wait();
if (response.IsCompleted)
{
var stream = response.Result.Content.ReadAsStreamAsync();
stream.Wait();
using (var reader = new StreamReader(stream.Result))
{
result = reader.ReadToEnd();
}
}
return result;
}
/// <summary>
/// Content-Type:application/json
/// </summary>
/// <param name="apiUrl"></param>
/// <returns></returns>
public static string HttpGetJson(string apiUrl)
{
string result = string.Empty;
//client.DefaultRequestHeaders.Add("Authorization", $"{Token.type} {Token.access_token}");
var response = client.GetAsync(apiUrl);
response.Wait();
if (response.IsCompleted)
{
var stream = response.Result.Content.ReadAsStreamAsync();
stream.Wait();
using (var reader = new StreamReader(stream.Result))
{
result = reader.ReadToEnd();
}
}
return result;
}
/// <summary>
/// Content-Type:application/x-www-form-urlencoded
/// </summary>
/// <param name="apiUrl"></param>
/// <param name="dict"></param>
/// <returns></returns>
public static string HttpPostForm(string apiUrl, IDictionary<string, string> dict)
{
string result = string.Empty;
//client.DefaultRequestHeaders.Add("Authorization", $"{Token.type} {Token.access_token}");
var httpContent = new FormUrlEncodedContent(dict);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = client.PostAsync(apiUrl, httpContent);
response.Wait();
if (response.IsCompleted)
{
var stream = response.Result.Content.ReadAsStreamAsync();
stream.Wait();
using (var reader = new StreamReader(stream.Result))
{
result = reader.ReadToEnd();
}
}
return result;
}
}
原文地址:https://www.cnblogs.com/wusirAaron/p/10991242.html