C# http post請求幫助類


using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;

namespace CommonSD
{
    public class HttpPostHelper
    {
        public static string Post(string url, string postData)
        {
            return Post(url, postData, "application/x-www-form-urlencoded");
        }

        public static string Post(string url, string postData, string contentType)
        {
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
            request.ContentType = contentType;
            request.Method = "POST";
            request.Timeout = 300000;

            byte[] bytes = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = bytes.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(bytes, 0, bytes.Length);
            writer.Close();

            HttpWebResponse response = (HttpWebResponse) request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8);
            string result = reader.ReadToEnd();
            response.Close();
            return result;
        }

        public static string Post(string url, string postData, string userName, string password)
        {
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
            request.ContentType = "text/html; charset=UTF-8";
            request.Method = "POST";

            string usernamePassword = userName + ":" + password;
            CredentialCache credentialCache =
                new CredentialCache {{new Uri(url), "Basic", new NetworkCredential(userName, password)}};
            request.Credentials = credentialCache;
            request.Headers.Add("Authorization",
                "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));

            byte[] bytes = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = bytes.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(bytes, 0, bytes.Length);
            writer.Close();

            HttpWebResponse response = (HttpWebResponse) request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.ASCII);
            string result = reader.ReadToEnd();
            response.Close();
            return result;
        }

        //static CookieContainer cookie = new CookieContainer();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url">請求的servlet地址,不帶參數</param>
        /// <param name="postData"></param>
        /// <returns>請求的參數,key=value&key1=value1</returns>
        public static string doHttpPost(string url, string postData)
        {
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
            SetHeaderValue(request.Headers, "Content-Type", "application/json");
            SetHeaderValue(request.Headers, "Accept", "application/json");
            SetHeaderValue(request.Headers, "Accept-Charset", "utf-8");
            request.Method = "POST";
            request.Timeout = 300000;

            byte[] bytes = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = bytes.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(bytes, 0, bytes.Length);
            writer.Close();

            HttpWebResponse response = (HttpWebResponse) request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8);
            string result = reader.ReadToEnd();
            response.Close();
            return result;
        }

        /// <summary>
        /// 偶發性超時時試看看
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string HttpPostForTimeOut(string url, string postData)
        {
            //System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            //watch.Start();
            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(postData);
            request.Timeout = 20 * 600 * 1000;


            ServicePointManager.Expect100Continue = false;
            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(postData);
            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 ?? throw new InvalidOperationException(), Encoding.GetEncoding("utf-8"));
            string registerResult = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return registerResult;
        }


        public static void SetHeaderValue(WebHeaderCollection header, string name, string value)
        {
            var property =
                typeof(WebHeaderCollection).GetProperty("InnerCollection",
                    BindingFlags.Instance | BindingFlags.NonPublic);
            if (property != null)
            {
                if (property.GetValue(header, null) is NameValueCollection collection) collection[name] = value;
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM