原创

c# post get

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using System.Drawing;
using System.Configuration;

using AForge;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Imaging;
using AForge.Imaging.Filters;
using ZXing;
using System.IO;
using System.Net;
namespace Default
{
    class Common
    {
        /// <summary> 
        /// 实现Base64加密解密 
        /// 作者:kaschie 
        /// 时间:2017
        /// </summary> 

        public sealed class Base64
        {
            /// <summary> 
            /// Base64加密 
            /// </summary> 
            /// <param name="codeName">加密采用的编码方式</param> 
            /// <param name="source">待加密的明文</param> 
            /// <returns></returns> 
            public static string EncodeBase64(Encoding encode, string source)
            {
                byte[] bytes = encode.GetBytes(source);
                string result = string.Empty;
                try
                {
                    result = Convert.ToBase64String(bytes);
                }

                catch
                {
                    result = source;
                }
                return result;
            }


            /// <summary> 
            /// Base64加密,采用utf8编码方式加密 
            /// </summary> 
            /// <param name="source">待加密的明文</param> 
            /// <returns>加密后的字符串</returns> 

            public static string EncodeBase64(string source)
            {
                return EncodeBase64(Encoding.UTF8, source);
            }

            /// <summary> 
            /// Base64解密 
            /// </summary> 
            /// <param name="codeName">解密采用的编码方式,注意和加密时采用的方式一致</param> 
            /// <param name="result">待解密的密文</param> 
            /// <returns>解密后的字符串</returns> 
            public static string DecodeBase64(Encoding encode, string result)
            {
                string decode = "";
                byte[] bytes = Convert.FromBase64String(result);
                try
                {
                    decode = encode.GetString(bytes);
                }

                catch
                {
                    decode = result;
                }
                return decode;
            }



            /// <summary> 
            /// Base64解密,采用utf8编码方式解密 
            /// </summary> 
            /// <param name="result">待解密的密文</param> 
            /// <returns>解密后的字符串</returns> 

            public static string DecodeBase64(string result)
            {
                return DecodeBase64(Encoding.UTF8, result);
            }
        }

        public sealed class PostOrGet
        {
            /// <summary>  
            /// 指定Post地址使用Get 方式获取全部字符串  
            /// </summary>  
            /// <param name="url">请求后台地址</param>  
            /// <param name="content">Post提交数据内容(utf-8编码的)</param>  
            /// <returns></returns>  
            public static string Post(string url, string content)
            {
                string result = "";
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";

                #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;
            }



            public static string HttpPostData(string url, string fileKeyName, string content,byte[] buffer)
            {

                string responseContent;

                var memStream = new MemoryStream();

                var webRequest = (HttpWebRequest)WebRequest.Create(url);

                // 边界符

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

                // 边界符

                var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");

                // var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

                // 最后的结束符

                var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");

                // 设置属性

                webRequest.Method = "POST";

                //webRequest.Timeout = timeOut;

                webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

                // 写入文件

                const string filePartHeader =

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

                     "Content-Type: application/octet-stream\r\n\r\n";

                var header = string.Format(filePartHeader, fileKeyName, "zz.jpg");

                var headerbytes = Encoding.UTF8.GetBytes(header);

                memStream.Write(beginBoundary, 0, beginBoundary.Length);

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

                //var buffer = new byte[1024];

                int bytesRead; // =0

                //while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                //{

                memStream.Write(buffer, 0, buffer.Length);

                // }

                // 写入字符串的Key

                var stringKeyHeader = "\r\n--" + boundary +

                                       "\r\nContent-Disposition: form-data; name=\"{0}\"" +

                                       "\r\n\r\n{1}\r\n";


                byte[] data = Encoding.UTF8.GetBytes(content);
                memStream.Write(data, 0, data.Length);



                // 写入最后的结束边界符

                memStream.Write(endBoundary, 0, endBoundary.Length);

                webRequest.ContentLength = memStream.Length;

                var requestStream = webRequest.GetRequestStream();

                memStream.Position = 0;

                var tempBuffer = new byte[memStream.Length];

                memStream.Read(tempBuffer, 0, tempBuffer.Length);

                memStream.Close();

                requestStream.Write(tempBuffer, 0, tempBuffer.Length);

                requestStream.Close();

                var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();

                using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(),

                                                                Encoding.GetEncoding("utf-8")))
                {

                    responseContent = httpStreamReader.ReadToEnd();

                }

                //fileStream.Close();

                httpWebResponse.Close();

                webRequest.Abort();

                return responseContent;

            }


            /// <summary>
            /// 发起httpPost 请求,可以上传文件
            /// </summary>
            /// <param name="url">请求的地址</param>
            /// <param name="files">文件</param>
            /// <param name="input">表单数据</param>
            /// <param name="endoding">编码</param>
            /// <returns></returns>
            public static string PostResponse(string url, byte[] files, Dictionary<string, string> input, Encoding endoding)
            {
                string message = string.Empty;
                string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = "multipart/form-data; boundary=" + boundary;
                request.Method = "POST";
                request.KeepAlive = true;
                //request.Credentials = CredentialCache.DefaultCredentials;
                request.Expect = "";

                MemoryStream stream = new MemoryStream();


                byte[] line = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
                byte[] enterER = Encoding.ASCII.GetBytes("\r\n");
                ////提交文件
                if (files != null)
                {
                    string fformat = "Content-Disposition:form-data; name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n";
                    //foreach (UpLoadFile file in files)
                    //{

                    stream.Write(line, 0, line.Length);        //项目分隔符
                    string s = string.Format(fformat, "fname", "test.jpg", "application/x-bmp");
                    byte[] data = Encoding.UTF8.GetBytes(s);
                    stream.Write(data, 0, data.Length);
                    stream.Write(files, 0, files.Length);
                    stream.Write(enterER, 0, enterER.Length);  //添加\r\n
                    ///}
                }


                //提交文本字段
                if (input != null)
                {
                    string format = "--" + boundary + "\r\nContent-Disposition:form-data;name=\"{0}\"\r\n\r\n{1}\r\n";    //自带项目分隔符
                    foreach (string key in input.Keys)
                    {
                        string s = string.Format(format, key, input[key]);
                        byte[] data = Encoding.UTF8.GetBytes(s);
                        stream.Write(data, 0, data.Length);
                    }

                }

                byte[] foot_data = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");      //项目最后的分隔符字符串需要带上--  
                stream.Write(foot_data, 0, foot_data.Length);

                request.ContentLength = stream.Length;
                Stream requestStream = request.GetRequestStream(); //写入请求数据
                stream.Position = 0L;
                stream.CopyTo(requestStream); //
                stream.Close();
                requestStream.Close();

                try
                {
                    HttpWebResponse response;
                    try
                    {
                        response = (HttpWebResponse)request.GetResponse();
                        try
                        {
                            using (var responseStream = response.GetResponseStream())
                            using (var mstream = new MemoryStream())
                            {
                                responseStream.CopyTo(mstream);
                                message = endoding.GetString(mstream.ToArray());
                                return message;
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                    catch (WebException ex)
                    {
                        //response = (HttpWebResponse)ex.Response;


                        //if (response.StatusCode == HttpStatusCode.BadRequest)
                        //{
                        //    using (Stream data = response.GetResponseStream())
                        //    {
                        //        using (StreamReader reader = new StreamReader(data))
                        //        {
                        //            string text = reader.ReadToEnd();
                        //            Console.WriteLine(text);
                        //        }
                        //    }
                        //}

                        throw ex;
                    }
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }

            }

            //testg
            public static void postfile(byte[] fileContentByte)
            {
                string url = "http://localhost:10673/WebForm1.aspx";

                string vbook_item_id = "69295";
                string vkechen_id = "8969";
                string fileName = "f.jpg";

                //byte[] fileContentByte = new byte[1024]; // 文件内容二进制

                #region 将文件转成二进制
                //fileContentByte = Common.StringLibrary.BitmapToBytes((Bitmap)this.pictureBox1.Image); // 二进制文件
                #endregion

                #region 定义请求体中的内容 并转成二进制

                string boundary = "ceshi";
                string Enter = "\r\n";

                string fileContentStr = "--" + boundary + Enter
                        + "Content-Type:application/octet-stream" + Enter
                        + "Content-Disposition: form-data; name=\"fileContent\"; filename=\"" + fileName + "\"" + Enter + Enter;

                string book_item_id = Enter + "--" + boundary + Enter
                        + "Content-Disposition: form-data; name=\"book_item_id\"" + Enter + Enter
                        + vbook_item_id;

                string kechen_id = Enter + "--" + boundary + Enter
            + "Content-Disposition: form-data; name=\"book_item_id\"" + Enter + Enter
            + vkechen_id;



                //var modelIdStrByte = Encoding.UTF8.GetBytes(modelIdStr);//modelId所有字符串二进制

                var fileContentStrByte = Encoding.UTF8.GetBytes(fileContentStr);//fileContent一些名称等信息的二进制(不包含文件本身)

                var book_item_idStrByte = Encoding.UTF8.GetBytes(book_item_id);//updateTime所有字符串二进制

                var kechen_idStrByte = Encoding.UTF8.GetBytes(kechen_id);//encrypt所有字符串二进制


                #endregion


                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "multipart/form-data;boundary=" + boundary;
                //request.ContentType = "application/x-www-form-urlencoded";

                using (Stream myRequestStream = request.GetRequestStream())  //;//定义请求流
                {
                    #region 将各个二进制 安顺序写入请求流 modelIdStr -> (fileContentStr + fileContent) -> uodateTimeStr -> encryptStr

                    //myRequestStream.Write(modelIdStrByte, 0, modelIdStrByte.Length);

                    myRequestStream.Write(fileContentStrByte, 0, fileContentStrByte.Length);
                    myRequestStream.Write(fileContentByte, 0, fileContentByte.Length);

                    myRequestStream.Write(book_item_idStrByte, 0, book_item_idStrByte.Length);

                    myRequestStream.Write(kechen_idStrByte, 0, kechen_idStrByte.Length);
                    myRequestStream.Close();
                    #endregion
                }

                string retString = string.Empty;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();//发送

                Stream myResponseStream = response.GetResponseStream();//获取返回值
                //获取响应内容  
                using (StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8))
                {
                    retString = reader.ReadToEnd();
                }
            }
        }
        public sealed class StringLibrary
        {
            public static string GetMac()
            {
                string result = string.Empty;
                string mac = "";
                ManagementClass mc;
                //mac地址  
                mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if (mo["IPEnabled"].ToString() == "True")
                    {
                        mac = mo["MacAddress"].ToString();
                    }
                }
                //输出  
                result = mac;
                return result;
            }

            /// <summary>
            /// 获取服务器URL
            /// </summary>
            /// <param name="str">URL后面参数</param>
            /// <returns></returns>
            public static string GetServerUrl(string str)
            {
                System.Configuration.ConfigurationManager.RefreshSection("appSettings");
                string result = string.Empty;
                result = string.Concat(System.Configuration.ConfigurationManager.AppSettings["ServerUrl"], str);
                return result;
            }

            /// <summary>
            /// 获取头像URL
            /// </summary>
            /// <param name="str"></param>
            /// <returns></returns>
            public static string GetImgUrl()
            {
                System.Configuration.ConfigurationManager.RefreshSection("appSettings");
                string result = string.Empty;
                result = System.Configuration.ConfigurationManager.AppSettings["ImgUrl"];
                return result;
            }

            public static string GetDeviceMonikerString()
            {
                System.Configuration.ConfigurationManager.RefreshSection("appSettings");
                string result = string.Empty;
                result = System.Configuration.ConfigurationManager.AppSettings["DeviceMonikerString"];
                return result;
            }

            public static string GetDeviceName()
            {
                System.Configuration.ConfigurationManager.RefreshSection("appSettings");
                string result = string.Empty;
                result = System.Configuration.ConfigurationManager.AppSettings["DeviceName"];
                return result;
            }

            public static bool GetIsPrint()
            {
                System.Configuration.ConfigurationManager.RefreshSection("appSettings");
                if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["IsPrint"]))
                    return false;
                else
                {
                    return Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsPrint"]);
                }
            }

            //获取打印机源
            //public static string GetPrintDevice()
            //{
            //    string result = string.Empty;

            //    result = System.Configuration.ConfigurationManager.AppSettings["PrintDevice"];
            //    return result;
            //}

            /// <summary>
            /// 獲取攝像頭像素比例
            /// </summary>
            /// <returns></returns>
            public static string GetVideoResolution()
            {
                System.Configuration.ConfigurationManager.RefreshSection("appSettings");
                string result = string.Empty;
                result = System.Configuration.ConfigurationManager.AppSettings["VideoResolution"].Trim();
                return result;
            }



            public static byte[] BitmapToBytes(Bitmap Bitmap)
            {
                MemoryStream ms = null;
                try
                {
                    ms = new MemoryStream();
                    //Bitmap.Save(ms, Bitmap.RawFormat);
                    Bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    byte[] byteImage = new Byte[ms.Length];
                    byteImage = ms.ToArray();
                    return byteImage;
                }
                catch (ArgumentNullException ex)
                {
                    throw ex;
                }
                finally
                {
                    ms.Close();
                }
            }

            public static Stream BytesToStream(byte[] bytes)
            {
                Stream stream = new MemoryStream(bytes);
                return stream;
            }


            /// <summary> 

            /// 改變相片樸素大小

            /// </summary> 

            /// <param name="serverImagePath">图片地址</param> 

            /// <param name="thumbnailImagePath">缩略图地址</param> 

            /// <param name="width">图片宽度</param> 

            /// <param name="height">图片高度</param> 

            /// <param name="p"></param> 

            public static System.Drawing.Image GetThumbnail(System.Drawing.Image serverImage, int width, int height)
            {
                System.Drawing.Image result = null;
                //System.Drawing.Image serverImage = System.Drawing.Image.FromFile(serverImagePath);


                //画板大小 

                int towidth = width;

                int toheight = height;

                //缩略图矩形框的像素点 

                int x = 0;

                int y = 0;

                int ow = serverImage.Width;

                int oh = serverImage.Height;

                if (ow > oh)
                {
                    toheight = serverImage.Height * width / serverImage.Width;
                }

                else
                {
                    towidth = serverImage.Width * height / serverImage.Height;
                }

                //新建一个bmp图片 

                System.Drawing.Image bm = new System.Drawing.Bitmap(width, height);

                //新建一个画板 

                System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bm);

                //设置高质量插值法 

                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

                //设置高质量,低速度呈现平滑程度 

                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                //清空画布并以透明背景色填充 

                g.Clear(System.Drawing.Color.White);

                //在指定位置并且按指定大小绘制原图片的指定部分 

                g.DrawImage(serverImage, new System.Drawing.Rectangle((width - towidth) / 2, (height - toheight) / 2, towidth, toheight),

                    0, 0, ow, oh,

                    System.Drawing.GraphicsUnit.Pixel);
                result = bm;
                serverImage.Dispose();

                //bm.Dispose();

                g.Dispose();

                //try
                //{

                //    //以jpg格式保存缩略图 

                //    bm.Save(thumbnailImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);

                //}

                //catch (System.Exception e)
                //{

                //    throw e;

                //}

                //finally
                //{

                //    serverImage.Dispose();

                //    bm.Dispose();

                //    g.Dispose();

                //}
                return result;
            }
        }
    }
}
复制代码
正文到此结束
该篇文章的评论功能已被站长关闭
本文目录