最近在开发钉钉服务端功能,钉钉的服务端开发与微信套路几乎一致,都是先拿到ACCESS_TOKEN后再按照接口要求请求。
这里我遇到了一个很奇怪的问题,在获取钉钉ACCESS_TOKEN时使用的是开发助手生成的GET访问代码,一切正常。
拿到ACCESS_TOKEN后用开发助手生成的POST访问代码 访问钉钉接口时却报错了,返回“操作繁忙”,代码我贴在下面:
根据钉钉要求,我将ContentType设置为application/json,其他都是代码生成,没有改动
[C#] 纯文本查看 复制代码 public static string Post(string url, string postData, string cookie = "")
{
HttpHelper http = new HttpHelper();
HttpItem item = new HttpItem()
{
URL = url,//URL 必需项
Method = "post",//URL 可选项 默认为Get
IsToLower = false,//得到的HTML代码是否转成小写 可选项默认转小写
Cookie = cookie,//字符串Cookie 可选项
Referer = "",//来源URL 可选项
Postdata = postData,//Post数据 可选项GET时不需要写
Timeout = 10000,//连接超时时间 可选项默认为100000
ReadWriteTimeout = 30000,//写入Post数据超时时间 可选项默认为30000
UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",//用户的浏览器类型,版本,操作系统 可选项有默认值
ContentType = "application/json",//返回类型 可选项有默认值
Allowautoredirect = false,//是否根据301跳转 可选项
ResultType = ResultType.String
};
HttpResult result = http.GetHtml(item);
string html = result.Html;
return html;
}
多次尝试无果后,我改用HttpWebRequest类一次成功,我把代码帖在下面:
[C#] 纯文本查看 复制代码 public static string Post_JSON(string url, string postData, string cookie = "")
{
string result = "";
byte[] bt = System.Text.Encoding.UTF8.GetBytes(postData);
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new Uri(url));
req.Timeout = 3000;
req.KeepAlive = false; //防止链接中断无响应
req.ProtocolVersion = System.Net.HttpVersion.Version10;
req.Method = "POST";
req.ContentType = "application/json";
req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
if (!string.IsNullOrEmpty(cookie))
{
req.Headers["Cookie"] = cookie;
}
try
{
using (System.IO.Stream streamReq = req.GetRequestStream())
{
streamReq.Write(bt, 0, bt.Length);
streamReq.Close();
streamReq.Dispose();
System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)req.GetResponse();
using (System.IO.StreamReader reader = new System.IO.StreamReader(res.GetResponseStream(), System.Text.Encoding.UTF8))
{
result = reader.ReadToEnd();
reader.Close();
reader.Dispose();
res.Close();
req.Abort();
}
}
}
catch
{
ConsoleColor Color = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(snow.时间处理(2, true) + " " + url + " POST发送失败。");
Console.ForegroundColor = Color;
result = "";
}
return result;
}
百度搜索了一下,之前已经有人遇到类似的问题,最后是“放弃WebClient类改用HttpWebRequest类”解决的。
所以请教一下苏飞老师,可能是哪里出错了? |