C# 進行HTTP POST myStreamWriter.Write(postDataStr); 請求被中止: 請求已被取消。
阿新 • • 發佈:2019-01-31
記錄下
public string HttpPost(string Url, string postDataStr) { System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); try { System.GC.Collect(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.ContentType = "application/json"; //request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr); int a = Encoding.UTF8.GetByteCount(postDataStr); request.Timeout= 20 * 600 * 1000; System.Net.ServicePointManager.Expect100Continue = false; System.Net.ServicePointManager.DefaultConnectionLimit = 200; request.KeepAlive = false; request.ProtocolVersion = HttpVersion.Version10; Stream myRequestStream= request.GetRequestStream(); StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("utf-8"));//如果JSON有中文則是UTF-8 myStreamWriter.Write(postDataStr); myStreamWriter.Close();//請求中止,是因為長度不夠,還沒寫完就關閉了. HttpWebResponse response = (HttpWebResponse)request.GetResponse(); watch.Stop(); //停止監視 TimeSpan timespan = watch.Elapsed; //獲取當前例項測量得出的總時間 System.Diagnostics.Debug.WriteLine("開啟視窗程式碼執行時間:{0}(毫秒)", timespan.TotalMinutes); //總毫秒數 Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } catch (Exception ex) { throw ex; watch.Stop(); //停止監視 TimeSpan timespan = watch.Elapsed; //獲取當前例項測量得出的總時間 System.Diagnostics.Debug.WriteLine("開啟視窗程式碼執行時間:{0}(毫秒)", timespan.TotalMinutes); //總毫秒數 return ""; } }