您的位置:首页 > 编程语言 > C#

C# POST,GET 提交数据

2016-12-28 16:59 381 查看
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

using System.Net;

using System.IO.Compression;

namespace Common

{

    public class HttpCommon

    {

        public static string GetUrlContent(string url, Encoding encode)

        {

            WebRequest request = (HttpWebRequest)WebRequest.Create(url);//为指定的 URI 方案初始化新的 System.Net.WebRequest 实例

            request.UseDefaultCredentials = false;

            WebResponse response = request.GetResponse();

            Stream resStream = response.GetResponseStream();

            StreamReader sr = new StreamReader(resStream, encode);

            string txt = sr.ReadToEnd();

            resStream.Close();

            return txt;

        }

        public static string GetUrlContent(string url, Encoding encode, CookieCollection cookies, out string setCookie, string cookieDomain)

        {

            string location;

            return SubmitUrlContent(url, "get", encode, cookies, cookieDomain, null, null, out setCookie, false, out location).ToString();

        }

        public static string PostUrlContent(string url, Encoding encode, Dictionary<string, string> Paras)

        {

            string setCookie, location;

            return SubmitUrlContent(url, "post", encode, null, null, Paras, null, out setCookie, false, out location).ToString();

        }

        /// <summary>

        /// get或post

        /// </summary>

        /// <param name="url"></param>

        /// <param name="type">get或post</param>

        /// <param name="encode"></param>

        /// <param name="Cookies"></param>

        /// <param name="cookieDomain"></param>

        /// <param name="Paras">参数</param>

        /// <param name="Files">文件Dictionary<string, byte[]></param>

        /// <returns></returns>

        public static object SubmitUrlContent(string url, string type, Encoding encode, CookieCollection Cookies, string cookieDomain, Dictionary<string, string> Paras, List<RequestFile> Files, out string setCookie, bool ReturnByte, out string location)

        {

            try

            {

                #region get处理参数

                if (type.ToUpper() == "GET")

                {

                    if (Paras != null)

                    {

                        url = GetUrlByParams(url, Paras);

                    }

                }

                #endregion

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//为指定的 URI 方案初始化新的 System.Net.WebRequest 实例

                request.Method = type.ToUpper();

                request.AllowWriteStreamBuffering = true;

                request.Credentials = System.Net.CredentialCache.DefaultCredentials;

                request.MaximumResponseHeadersLength = -1;

                request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";

                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";

                request.ContentType = "application/x-www-form-urlencoded";

                request.Headers.Add("Accept-Language", "zh-cn");

                //request.Headers.Add("Accept-Encoding", "gzip,deflate");

                request.KeepAlive = true;

                request.AutomaticDecompression = DecompressionMethods.GZip;

                request.Referer = "http://www.police.sh.cn/shga/index.html";

                #region 添加cookie

                if (Cookies != null && Cookies.Count > 0)

                {

                    CookieContainer cookies = new System.Net.CookieContainer();

                    cookies.Add(Cookies);

                    request.CookieContainer = cookies;

                }

                #endregion

                #region post处理参数及文件

                if (type.ToUpper() != "GET")

                {

                    string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");

                    byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

                    request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);

                    Stream rs = request.GetRequestStream();

                    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";

                    #region 添加参数

                    if (Paras != null)

                    {

                        foreach (KeyValuePair<string, string> item in Paras)

                        {

                            rs.Write(boundarybytes, 0, boundarybytes.Length);

                            string formitem = string.Format(formdataTemplate, item.Key, item.Value);

                            byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);

                            rs.Write(formitembytes, 0, formitembytes.Length);

                        }

                    }

                    #endregion

                    #region 添加文件

                    if (Files != null)

                    {

                        request.AllowWriteStreamBuffering = true;

                        string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";

                        Files.ForEach(f =>

                        {

                            rs.Write(boundarybytes, 0, boundarybytes.Length);

                            string header = string.Format(headerTemplate, f.paraName, f.fileName, request.ContentType);

                            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

                            rs.Write(headerbytes, 0, headerbytes.Length);

                            rs.Write(f.content, 0, f.content.Length);

                        });

                    }

                    #endregion

                    byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

                    rs.Write(trailer, 0, trailer.Length);

                    rs.Close();

                }

                #endregion

                WebResponse response0 = null;

                HttpWebResponse response;

                object txt;

                try

                {

                    response0 = request.GetResponse();

                    response = (HttpWebResponse)response0;

                    Stream resStream = response0.GetResponseStream();

                    if (response.ContentEncoding.ToLower().Contains("gzip"))

                        resStream = new GZipStream(resStream, CompressionMode.Decompress);

                    else if (response.ContentEncoding.ToLower().Contains("deflate"))

                        resStream = new DeflateStream(resStream, CompressionMode.Decompress);

                    if (ReturnByte)

                    {

                        MemoryStream ms = new MemoryStream();

                        byte[] buffer = new byte[4096];

                        int len;

                        len = resStream.Read(buffer, 0, 4096);

                        while (len > 0)

                        {

                            ms.Write(buffer, 0, len);

                            len = resStream.Read(buffer, 0, 4096);

                        }

                        txt = ms.GetBuffer();

                    }

                    else

                    {

                        StreamReader sr = new StreamReader(resStream, encode);

                        txt = sr.ReadToEnd();

                    }

                    resStream.Close();

                    request = null;

                }

                catch (WebException ex)

                {

                    if (response0 != null)

                    {

                        response0.Close();

       
ce25
                response0 = null;

                    }

                    request = null;

                    if (ReturnByte)

                    {

                        txt = new byte[0];

                    }

                    else

                    {

                        txt = "";

                    }

                    response = ex.Response as HttpWebResponse;

                }

                setCookie = response.Headers["Set-Cookie"];

                location = response.Headers["Location"];

                if (string.IsNullOrWhiteSpace(location))

                    location = response.ResponseUri.AbsoluteUri;

                return txt;

            }

            catch (Exception ex)

            {

                throw new Exception("访问url(" + url + ")出错:" + ex.Message);

            }

        }

        private static string GetUrlByParams(string oldUrl, Dictionary<string, string> paramss)

        {

            if (paramss == null || paramss.Count == 0)

                return oldUrl;

            StringBuilder sb = new StringBuilder();

            foreach (KeyValuePair<string, string> kv in paramss)

            {

                sb.Append("&" + kv.Key + "=" + System.Web.HttpUtility.UrlEncode(kv.Value));

            }

            if (oldUrl.Contains("?"))

            { return oldUrl + sb.ToString(); }

            return oldUrl + "?" + sb.Remove(0, 1).ToString();

        }

    }

    public class RequestFile

    {

        public string paraName { get; set; }

        public string fileName { get; set; }

        public byte[] content { get; set; }

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  .net