在一次項目中,在給客戶做系統時,需要調用客戶的系統獲取數據,客戶提供了獲取Token和獲取數據的介面,用戶名和密碼,認證方式是基於Bearer的,通過學習和找資料,提供一個C#示例 一個C#示例 1、傳入語句獲取數據 /// <summary> /// 傳入語句獲取數據 /// </summary> ...
在一次項目中,在給客戶做系統時,需要調用客戶的系統獲取數據,客戶提供了獲取Token和獲取數據的介面,用戶名和密碼,認證方式是基於Bearer的,通過學習和找資料,提供一個C#示例
一個C#示例
1、傳入語句獲取數據
/// <summary>
/// 傳入語句獲取數據
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public async Task<string> ThirdSystemDataPostAsync(string param,string dataUrlAddress)
{
string token = await Bearer_TokenPostAsync();
_logger.Warn($"獲取Token結構:{token}");
string responseString = string.Empty;
try
{
var tokenJson = JsonConvert.DeserializeObject<TokenResultDto>(token);
_logger.Warn($"獲取Token值參數據:{tokenJson}");
//跳過ssl驗證
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
// 創建HttpWebRequest對象
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(dataUrlAddress);
_logger.Warn($"入參數據:{param}");
_logger.Warn($"智慧系統數據地址:{dataUrlAddress}");
// 設置Post調⽤⽅法
httpRequest.Method = "Post";
//設置參數傳輸類型
httpRequest.ContentType = " application/json; charset=utf-8";
// 設置Http Bearer認證的請求頭
httpRequest.Headers.Add("Authorization", "Bearer " + tokenJson.accessToken);
//傳輸參數格式轉換
byte[] bytesRequestData = Encoding.UTF8.GetBytes(param);
//_logger.Warn($"入參數據格式轉換:{bytesRequestData}");
httpRequest.ContentLength = bytesRequestData.Length;
Stream postStream = await httpRequest.GetRequestStreamAsync();
postStream.Write(bytesRequestData, 0, bytesRequestData.Length);
postStream.Close();
//獲取設置身份認證及請求超時時間
SetWebRequest(httpRequest);
// HttpWebRequest發起調⽤
using (HttpWebResponse myResponse = (HttpWebResponse)httpRequest.GetResponse())
{
//myResponse.StatusCode
// StreamReader對象
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
// 返回結果
responseString = sr.ReadToEnd();
_logger.Warn($"調用智慧系統返回結果數據:{responseString}");
return responseString;
}
}
catch (Exception ex)
{
//返回錯誤信息
responseString = ex.ToString();
}
return responseString;
}
2、獲取token
/// <summary>
/// 獲取token
/// </summary>
/// <returns></returns>
private async Task<string> Bearer_TokenPostAsync(string sSoUrlAddress,string userName,string userPassword)
{
string responseString = string.Empty;
try
{
// 創建HttpWebRequest對象
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(sSoUrlAddress);
_logger.Warn($"智慧系統Token地址:{sSoUrlAddress}");
// 設置Post調⽤⽅法
httpRequest.Method = "Post";
//設置參數傳輸類型
httpRequest.ContentType = " application/json; charset=utf-8";
// 設置用戶名和密碼
var usermesg = new UserMesgInput()
{
Username = userName,
Password = userPassword,
UserDetail = true
};
string base64 = JsonConvert.SerializeObject(usermesg);
//傳輸參數格式轉換
byte[] bytesRequestData = Encoding.UTF8.GetBytes(base64);
//_logger.Warn($"入參數據格式轉換:{bytesRequestData}");
httpRequest.ContentLength = bytesRequestData.Length;
Stream postStream = await httpRequest.GetRequestStreamAsync();
postStream.Write(bytesRequestData, 0, bytesRequestData.Length);
postStream.Close();
//獲取設置身份認證及請求超時時間
SetWebRequest(httpRequest);
_logger.Warn($"獲取設置身份認證及請求超時時間");
// HttpWebRequest發起調⽤
using (HttpWebResponse myResponse = (HttpWebResponse)httpRequest.GetResponse())
{
_logger.Warn($"StreamReader對象");
// StreamReader對象
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
//_logger.Warn($"返回結果{sr.ReadToEnd()}");
// 返回結果
responseString = sr.ReadToEnd();
_logger.Warn($"調用智慧系統返回結果Token:{responseString}");
//return responseString;
}
}
catch (Exception ex)
{
//返回錯誤信息
responseString = ex.ToString();
}
return responseString;
}
3、獲取設置身份認證及請求超時時間
/// <summary>
/// 獲取設置身份認證及請求超時時間
/// </summary>
/// <param name="request"></param>
private static void SetWebRequest(HttpWebRequest request)
{
request.Credentials = CredentialCache.DefaultCredentials;
request.Timeout = 1000000;
}
4、在我使用的時候出現了下麵的錯誤,通過查找是證書的問題,因為客戶的web訪問使用的IP地址訪問,所以在代碼中要加入跳過ssl驗證的一行代碼
System.Net.WebException: The SSL connection could not be established, see inner exception. The remote certificate is invalid according to the validation procedure.