最近在做一个对接金蝶云的项目,发现有些时候会存在返回无响应的情况,经查发现是金蝶官方提供的API说明中的http访问类中存在问题。特将改进后的代码贴出来以供大家探讨。
以下http访问类可以适用市面上绝大部分的API接口。
附件为完整CS文件
/// <summary>
/// webAPI接口访问
/// </summary>
/// <param name="mUrl">接口地址</param>
/// <param name="Method">提交方法</param>
/// <param name="postData">参数</param>
/// <param name="ContentType">ContentType</param>
/// <param name="EndcodeType">字符编码格式</param>
/// <returns>返回webAPI返回的结果</returns>
public String send(String mUrl, String Method, String postData, String ContentType, String EndcodeType, bool UrlCode = true, String mHeadJson = "")
{
try
{
HttpWebRequest request = null;
if (mUrl.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
request = WebRequest.Create(mUrl) as HttpWebRequest;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request.ProtocolVersion = HttpVersion.Version11;
// 这里设置了协议类型。
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2;
request.KeepAlive = false;
ServicePointManager.CheckCertificateRevocationList = true;
ServicePointManager.DefaultConnectionLimit = 1024;
ServicePointManager.Expect100Continue = false;
}
else
{
request = (HttpWebRequest)WebRequest.Create(mUrl);
}
request.CookieContainer = Cookie;
request.Timeout = 1000 * 60 * 10;//发送超时时间10min
request.ReadWriteTimeout = 1000 * 60 * 1; //接受响应超时时间1min 增加点,关键改造处
request.Method = Method; //使用get方式发送数据
request.ContentType = ContentType;
request.Referer = null;
request.AllowAutoRedirect = true;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
request.Accept = "*/*";
if (mHeadJson != "") //关键改造
{
JObject jh = JsonConvert.DeserializeObject(mHeadJson) as JObject;
foreach (var p in jh.Properties().ToArray())
{
request.Headers.Add(p.Name, jh[p.Name].Value<string>()); //添加表头参数,有些网站是使用Auth认证的,需要在请求头中添加参数
}
}
//POST提交,需要提交参数
if (Method.ToLower() == "post")
{
//防止参数为空报错
if (string.IsNullOrEmpty(postData))
{
postData = "";
}
if (UrlCode == true)
{
postData = HttpUtility.UrlEncode(postData);
}
var data = Encoding.GetEncoding(EndcodeType).GetBytes(postData); //注意字符集编码
Stream newStream = request.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
}
//获取网页响应结果
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
string result = string.Empty;
using (StreamReader sr = new StreamReader(stream))
{
result = sr.ReadToEnd();
}
response.Close();
return result;
}
catch (WebException e)
{
return "{\"KDDIYErr\":{\"code\":\"" + e.Status + "\",\"description\":\"" + e.Message + "\"}}";
}
}
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
cCEEHttps.zip(3.08KB)
推荐阅读
您的鼓励与嘉奖将成为创作者们前进的动力,如果觉得本文还不错,可以给予作者创作打赏哦!
请选择打赏金币数 *