网络数据推送
一、通用数据推送代码
下面是优化后的代码:
private async Task<string> PostResponse(string url, string postDataStr, string accessToken)
{
string htmlUrl = url + (string.IsNullOrEmpty(accessToken) ? "" : "?access_token=" + accessToken);
string apiUrl = apiurl.TrimEnd('/') + "/";
var client = new HttpClient();
client.BaseAddress = new Uri(apiUrl);
var requestMessage = new HttpRequestMessage(HttpMethod.Post, htmlUrl);
requestMessage.Content = new StringContent(postDataStr, Encoding.UTF8, "application/json");
try
{
var response = await client.SendAsync(requestMessage).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return result;
}
else
{
var error = new { code = -999999, msg = response.StatusCode };
return JsonConvert.SerializeObject(error);
}
}
catch (Exception ex)
{
return $"PostResponse_token:url{{{url}}}{ex.Message}{ex.StackTrace}";
}
}
优化说明:
-
将参数名称的首字母改为小写,符合 C# 命名规范。
-
为了提高代码的可读性,将一些变量的命名更改为更有意义的名称。
-
将重复代码提取出来,避免出现重复代码。
-
简化代码,去掉一些不必要的代码,如变量 str。
-
使用 string.IsNullOrEmpty() 方法判断字符串是否为空。
-
使用 Encoding.UTF8 替换 System.Text.Encoding.UTF8。
-
为了提高代码的可读性,将一些代码进行了格式化和缩进。
二、加了接口鉴权的数据推送代码:
/// <summary>
/// 上海联通数据推送接口 2023-4-1 lzh
/// </summary>
/// <param name="Url">获取令牌地址</param>
/// <param name="postDataStr">发送数据</param>
/// <param name="Token">令牌</param>
/// <returns></returns>
private async Task<string> PostTokenResponse(string Url, string postDataStr,string Token)
{
NLogHelp.WriteError("PostResponseToken2:" + Url + postDataStr);
// 1、准备Url
var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"{Url}");
// 2、准备参数postDataStr
requestMessage.Content = new StringContent(postDataStr, System.Text.Encoding.UTF8, "application/json");
string retString = "";
try
{
// 1/ 创建一个HttpClient
var _client = _clientFactory.CreateClient("FrontendApiurl2");
// 2、HttpClient 请求头Bearer
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
var response = await _client.SendAsync(requestMessage).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
// 3、得到结果
var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
retString = result;
}
else
{
retString = JsonConvert.SerializeObject(new { code = -999999, msg = response.StatusCode });
}
}
catch (Exception ex)
{
return "PostResponse_token:url{" + Url + "}" + ex.StackTrace;
}
return retString;
}