使用C#httpwebrequest请求接口返回code提示缺少参数version,但我已经添加过version了,我再把url拷贝到浏览器上运行又提示signature错误,请问是什么原因?
部分代码
static void Main(string[] args)
{
string url = "https://aai.tencentcloudapi.com";
SortedDictionary<string, string> dic = new SortedDictionary<string, string>();
dic.Add("Action", "TextToVoice");
dic.Add("Version", "2018-05-22");
dic.Add("Region", "ap-beijing");
dic.Add("Text", "测试文本");
dic.Add("SessionId", "sessionid-1234");
dic.Add("ModelType", "1");
dic.Add("Timestamp", GetCurrentTimeUnix(0));
//dic.Add("Expired", GetCurrentTimeUnix(3600));
dic.Add("Nonce", "555555");
dic.Add("SecretId", "AKIDTp25wciVikbHn7lDymRwFNJ3czA9qRUP");
StringBuilder builder = new StringBuilder();
builder.Append("https://aai.tencentcloudapi.com/?");
int i = 0;
foreach (var item in dic)
{
if (i > 0)
{
builder.Append("&");
}
builder.AppendFormat("{0}={1}", item.Key, item.Value);
i++;
}
string miwen = HmacSha1AndBase64(builder.ToString(), "077RbcS6YovrdDcrvmX7WlxyoSuDKJ7j");
Console.WriteLine(builder.ToString());
Console.WriteLine(miwen);
dic.Add("Signature", miwen);
builder.Append("&Signature="+miwen);
Console.WriteLine(Post(builder.ToString()));
Console.ReadKey();
Console.WriteLine(Post(builder.ToString()));
Console.ReadKey();
}
public static string HmacSha1AndBase64(string mk, string secretkey)
{
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = Encoding.UTF8.GetBytes(secretkey);
byte[] dataBuffer = Encoding.UTF8.GetBytes(mk);
byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
return Convert.ToBase64String(hashBytes);
}
//获取时间戳
public static string GetCurrentTimeUnix(int second)
{
//设置时间戳
DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local);
long time = (int)(DateTime.Now.AddHours(-8) - dt).TotalSeconds+second;
String Timestamp = time.ToString();
return Timestamp;
}
//带键值对的post方法
public static string Post(string url)
{
/*
* 定义httprequest链接
* */
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
/*
* 设置httprequest属性
* */
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("Authorization", "VVerIEkz2OAuSBdNtH6W2M1xal0=");
/*
* 定义httpresponse
* */
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
/*
* 接收response的数据
* */
string returnresult = string.Empty;
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
{
returnresult = sr.ReadToEnd();
sr.Close();
}
stream.Close();
}
return returnresult;
}
相似问题