#region 调用API接口的方法
private static string httpApi(string url, string jsonStr = "",
string type = "POST",string TokenStr= "")
{
if (string.IsNullOrEmpty(url))
{
//LogHelper.WriteLog("API链接地址为空,配置INI文件缺失");
return null;
}
string result = "";//返回结果
try
{
Encoding encoding = Encoding.UTF8;
HttpWebResponse response;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//webrequest请求api地址
request.Headers.Add("Authorization", "Bearer " + "");
request.Credentials = CredentialCache.DefaultCredentials;
request.Accept = "text/html,application/xhtml+xml,*/*";
request.ContentType = "application/json";
request.Method = type.ToUpper().ToString();//get或者post
if (!string.IsNullOrEmpty(jsonStr))//Get请求无需拼接此参数
{
byte[] buffer = encoding.GetBytes(jsonStr);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
}
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = (HttpWebResponse)ex.Response;
}
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
result = reader.ReadToEnd();
reader.Close();
}
if (response.StatusCode != HttpStatusCode.OK)//返回响应码非成功格式化数据后返回
{
result = "Exception:" + JsonConvert.DeserializeObject<string>(result);
}
return result;
}
catch (WebException ex)
{
return "Exception:" + ex.Message;
}
}
#endregion
//调用
string Token = httpApi(“https://api.www,baidu.com/api/authorize/login”, Json,“POST”,"");
dynamic json = Newtonsoft.Json.Linq.JToken.Parse(Token) as dynamic;
int Code= json.statusCode;
string AcconToken = json.data.accessToken;
if (!Code.Equals(200))
{
MessageBox.Show(json.errors);
return;
}