类别:程序开发
日期:2023-10-20 浏览:2304 评论:0
使用HttpWebRequest GET方法来调用REST服务.我收到错误: – ***’Content-Type’标头必须使用适当的属性或方法进行修改.参数名称:name.***我从stackoverflow检查了所有与此问题相关的答案.)
public string PostUrl(string url, string json) { string appkey = "fa3a4c9efe16449fb1d4b"; //appkey string appsecret = "9D261499DF754A53A374BAB662C3CF49"; //appsecret string sign = ""; //验签 var timestamp = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000; string nonce = Guid.NewGuid().ToString(); string result = "x-aep-appkey=" + appkey + "&x-aep-nonce=" + nonce + "&x-aep-timestamp=" + timestamp; //sign = ZZAYwebservice.Models.sm3.Sm3Crypto.ToSM3HexStr(result, appsecret); sign = Sm3Crypto.ToSM3string(result, appsecret); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.ContentType = "application/json"; //req.Headers.Add("Content-Type", "application/json"); req.Headers.Add("x-aep-timestamp", timestamp.ToString()); req.Headers.Add("x-aep-appkey", appkey); req.Headers.Add("x-aep-nonce", nonce); req.Headers.Add("x-aep-signature", sign); req.Method = "POST"; req.Timeout = 30000;//设置请求超时时间,单位为毫秒 req.ContentType = "application/json"; byte[] data = Encoding.UTF8.GetBytes(json); req.ContentLength = data.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(data, 0, data.Length); reqStream.Close(); } HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Stream stream = resp.GetResponseStream(); //获取响应内容 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { result = reader.ReadToEnd(); } return result; }
解决方法:
我也结束了这个问题.但意识到问题在于如何设置内容类型.
正确的设置方法是
request.ContentType = "application/json";
发表评论 / 取消回复