public static string Post(object param ,string url)
{
#region
try
{
string resultString = "";
ApiRequest apiRequest = new ApiRequest();
apiRequest.httpMethod = "POST";
apiRequest.body = param;
apiRequest.apiPath = url;
DateTime currentTime = DateTime.UtcNow;
TimeSpan timeSpan = currentTime - new DateTime(1970, 1, 1, 0, 0, 0, 0);
long timestamp = Convert.ToInt64(timeSpan.TotalMilliseconds);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = apiRequest.httpMethod;
request.Timeout = DEFAULT_TIMEOUT;
request.Headers.Add(ApiConstants.HEADER_X_CA_KEY, APP_KEY);
request.Headers.Add(ApiConstants.HEADER_X_CA_TIMESTAMP, timestamp.ToString());
request.Headers.Add(ApiConstants.HEADER_X_CA_NONCE, System.Guid.NewGuid().ToString());
request.Accept = ApiConstants.CONTENT_TYPE_JSON;
request.Date = currentTime;
Stream requestStream = request.GetRequestStream();
if (!string.IsNullOrEmpty(apiRequest.GetBodyContent()))
{
byte[] bytes = Encoding.UTF8.GetBytes(apiRequest.GetBodyContent());
request.ContentType = ApiConstants.CONTENT_TYPE_JSON;
//request.ContentLength = bytes.Length;
string stringToSign = ApiUtils.buildStringToSign(apiRequest, request);
string signature = ApiUtils.getSignature(stringToSign, APP_SECRET);
request.Headers.Add(ApiConstants.HEADER_X_CA_SIGNATURE, signature);
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
}
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
//获取响应内容
using (Stream stream = resp.GetResponseStream())
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
resultString = reader.ReadToEnd();
}
return resultString;
}
catch (Exception ex)
{
return null;
}
#endregion
}
C# Post请求
于 2022-02-21 17:06:30 首次发布