代碼是這樣的:這怎么解決 各位大佬
public R HttpPostJson<T, R>(string url, List<T> t, string projectCode = "", string hosCode = "", string hosName = "", string timespan = "", string key = "")
where T : class where R : class
{
projectCode = ElecInfo.projectCode;
hosCode = ElecInfo.hosCode;
hosName = ElecInfo.hosName;
key = ElecInfo.key;
//時間戳
timespan = CommonHelper.GetCurrentTimeStamp().ToString();
#region 日志
//寫入參日志
LoggerHelper.Write(string.Format("\r\n時間:{0},\r\n 地址:{1},\r\n 介面:{2},\r\n 內容:{3}\r\n",
DateTime.Now, url, t.ToString().Split('.')[t.ToString().Split('.').Length - 1].TrimEnd(']'),
ListToJsonSerializer(t)), LogsType.InParm);
#endregion
try
{
ServicePointManager.DefaultConnectionLimit = 100;
///根據URL創建HttpWebRequest物件
HttpWebRequest httpWeb = (HttpWebRequest)HttpWebRequest.Create(url);
//設定請求方式為post請求
httpWeb.Method = "POST";
//httpWeb.Accept = "HTTP";
httpWeb.ContentType = "application/json;charset=UTF-8";
//組合json內容
//1.組裝header內容
SetHeaderValue(httpWeb.Headers, "Content-Type", "application/json");
SetHeaderValue(httpWeb.Headers, "projectCode", projectCode);
SetHeaderValue(httpWeb.Headers, "hosCode", hosCode);
SetHeaderValue(httpWeb.Headers, "hosName", hosName);
//2.獲取header encryptData加密資料
var encryptData = GetHeaderEncryption(timespan);
if (string.IsNullOrWhiteSpace(encryptData)) return null;
SetHeaderValue(httpWeb.Headers, "encryptData", encryptData);
//3.組裝body部分
StringBuilder stringBuilder = new StringBuilder();
//序列化實體t
var body = ListToJsonSerializer<T>(t);
var dict = new SortedDictionary<string, string>
{
{"key", ElecInfo.key},
{"originaldata", body},
};
//加密body主體
var result = GetBodyEncryption(dict);
//把json轉換成
byte[] buffer = Encoding.UTF8.GetBytes(result);
httpWeb.ContentLength = buffer.Length;
httpWeb.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
httpWeb.Connection = "";
httpWeb.KeepAlive = false;
using (Stream stream = httpWeb.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);
stream.Close();
}
//在這里httpWeb.GetResponse()的時候 提示"無法從傳輸連接中讀取資料: 連接已關閉。”
using (HttpWebResponse response = httpWeb.GetResponse() as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
//得到密文 解密回傳 json資料
R r = JsonDeserializeObject<R>(GetDecrypt(reader.ReadToEnd()));
#region 日志
//寫出參日志
LoggerHelper.Write(string.Format("時間:{0},\r\n 地址:{1},\r\n 介面:{2},\r\n 內容:{3}\r\n",
DateTime.Now, url, t.ToString().Split('.')[t.ToString().Split('.').Length - 1].TrimEnd(']'),
GetDecrypt(reader.ReadToEnd())), LogsType.OutParm);
#endregion
return r;
}
}
}
catch (Exception ex)
{
#region 日志
//寫錯誤日志
LoggerHelper.Write(string.Format("時間:{0},\r\n 地址:{1},\r\n 介面:{2},\r\n 內容:{3}\r\n",
DateTime.Now, url, t.ToString().Split('.')[t.ToString().Split('.').Length - 1].TrimEnd(']'),
ex.Message.ToString()), LogsType.Error);
#endregion
return JsonDeserializeObject<R>(JsonSerializeObject(ex.Message));
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/55400.html
標籤:C#
上一篇:WebService超時
