2019独角兽企业重金招聘Python工程师标准>>>
一、维信支付退款错误:基础连接已经关闭的错误
原因:退款操作接口是https 的地址。
解决方案:发起请求时开启tls/ssl 通道,添加安全证书。
推荐示例代码1:
///
/// 指定Post地址使用Get 方式获取全部字符串
///
/// 请求后台地址
/// Post提交数据内容(utf-8编码的)
///
public static string PostSsl3(string url, string content)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
//添加证书
X509Certificate2 certificate = new X509Certificate2(@"F:\Mvc_Site\zzy\QL.MiniMall.LA_SZ\cert\apiclient_cert.p12", "1530564111", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
req.ClientCertificates.Add(certificate);
//设置安全模式
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
#region 添加Post 参数
byte[] data = Encoding.UTF8.GetBytes(content);
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
#endregion
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
解决方案代码示例2:
public static string PostWebRequest(string postUrl, string paramData)
{
string ret = string.Empty;
try
{
X509Certificate2 certificate = new X509Certificate2(@"E:\工作项目\apiclient_cert.p12", "1519238551", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet); //初始化证书
byte[] byteArray = Encoding.Default.GetBytes(paramData); //转化
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded";
webReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
webReq.ClientCertificates.Add(certificate); //添加证书
webReq.ContentLength = byteArray.Length;
Stream newStream = webReq.GetRequestStream(); //
newStream.Write(byteArray, 0, byteArray.Length);//写入参数
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse(); //这里报错
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
ret = sr.ReadToEnd();
newStream.Close();
sr.Close();
response.Close();
newStream.Close();
}
catch (Exception ex)
{
return ex.Message;
}
return ret;
}