向服务器发送Post或Get请求(封装好的)

 

  /// <summary>
        /// Web请求方式:1、Get 2、Post
        /// </summary>
        public enum RequestMethod
        {
            Get,
            Post
        }

  

        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="uploadfile"></param>
        /// <returns></returns>
        private static string SaveImage(HttpPostedFileBase uploadfile, string filePath)
        {
            string fileExtentsion = Path.GetExtension(uploadfile.FileName).ToLower();
            string tmpFileName = Guid.NewGuid().ToString("N").ToLower() + fileExtentsion;

            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            string serverLocalPath = Path.Combine(filePath, tmpFileName);
            uploadfile.SaveAs(serverLocalPath);
            return serverLocalPath;
        }

  

/// <summary>
        /// Web请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static string Request(string url, RequestMethod method, Dictionary<string, object> parameters)
        {
            UriBuilder URI = new UriBuilder(url);
            HttpWebRequest webRequest = null;
            Stream requestWriter = null;
            string responseData = BuildQueryString(parameters);
            URI.Query = responseData;
            webRequest = System.Net.WebRequest.Create(URI.Uri) as HttpWebRequest;
            webRequest.Method = method.ToString();
            webRequest.ServicePoint.Expect100Continue = false;

            byte[] data = Encoding.UTF8.GetBytes(responseData);

            if (method == RequestMethod.Post)
            {
                webRequest.ContentType = "application/x-www-form-urlencoded";
                requestWriter = webRequest.GetRequestStream();
                try
                {
                    requestWriter.Write(data, 0, data.Length);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    requestWriter.Close();
                    requestWriter = null;
                }
            }
            responseData = WebResponseGet(webRequest);
            webRequest = null;
            return responseData;
        }

  

   /// <summary>
        /// 当前请求转发至其他服务器(上传多张图片)
        /// </summary>
        /// <param name="_Content"></param>
        /// <param name="file"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string HttpUploadFileList(string url, RequestMethod method, Dictionary<string, object> parameters, List<HttpPostedFileBase> uploadfileList)
        {
            string result = string.Empty;
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = method.ToString();
            request.KeepAlive = true;
            request.Credentials = CredentialCache.DefaultCredentials;

            Stream stream = request.GetRequestStream();
            string template = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";

            #region request.form 参数
            foreach (string _key in parameters.Keys)
            {
                string value = Convert.ToString(parameters[_key]);
                stream.Write(boundarybytes, 0, boundarybytes.Length);
                string formitem = string.Format(template, _key, value);
                byte[] formitembytes = Encoding.UTF8.GetBytes(formitem);
                stream.Write(formitembytes, 0, formitembytes.Length);
            }
            #endregion

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

            #region 文件
            foreach (HttpPostedFileBase uploadfile in uploadfileList)
            {
                stream.Write(boundarybytes, 0, boundarybytes.Length);

                string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
                string header = string.Format(headerTemplate, "uploadfile", uploadfile.FileName, uploadfile.ContentType);
                byte[] headerbytes = Encoding.UTF8.GetBytes(header);
                stream.Write(headerbytes, 0, headerbytes.Length);

                byte[] imageData = null;
                using (BinaryReader binaryReader = new BinaryReader(uploadfile.InputStream))
                {
                    imageData = binaryReader.ReadBytes(uploadfile.ContentLength);
                }
                stream.Write(imageData, 0, imageData.Length);
            }
            #endregion

            byte[] bytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            stream.Write(bytes, 0, bytes.Length);

            stream.Close();
            result = WebResponseGet(request);
            request = null;
            return result;
        }

  

/// <summary>
        /// 读取数据
        /// </summary>
        /// <param name="webRequest">HttpWebRequest</param>
        /// <returns>根据参数条件返回相应的数据</returns>
        private static string WebResponseGet(HttpWebRequest webRequest)
        {
            StreamReader responseReader = null;
            string responseData = "";
            try
            {
                responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
                responseData = responseReader.ReadToEnd();
            }
            catch
            {
                throw;
            }
            finally
            {
                webRequest.GetResponse().GetResponseStream().Close();
                responseReader.Close();
                responseReader = null;
            }
            return responseData;
        }

  

        /// <summary>
        /// 将Dictionary<string,object>集合遍历成URL参数!
        /// </summary>
        /// <param name="config">Dictionary<string, object>config</param>
        /// <returns>Query</returns>
        public static string BuildQueryString(Dictionary<string, object> config)
        {
            List<string> paramList = new List<string>();
            foreach (KeyValuePair<string, object> item in config)
            {
                paramList.Add(string.Format("{0}={1}", item.Key, item.Value));
            }
            return string.Join("&", paramList.ToArray());
        }

  

 

猜你喜欢

转载自www.cnblogs.com/BounceGuo/p/10076215.html
0条评论
添加一条新回复