コード例 #1
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="param"></param>
        /// <returns></returns>
        public static T Get <T>(HttpParam param)
        {
            var str = Get(param);

            return(JSON.ToObject <T>(str));
        }
コード例 #2
0
        /// <summary>
        /// 文件上传至远程服务器。传入:Url、CookieContainer、PostParam、PostedFile
        /// </summary>
        public static string PostFile(HttpParam param)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(param.Url);

            request.CookieContainer = param.CookieContainer;
            request.Method          = "POST";
            request.Timeout         = 20000;
            request.Credentials     = System.Net.CredentialCache.DefaultCredentials;
            request.KeepAlive       = true;
            var boundary      = "----------------------------" + DateTime.Now.Ticks.ToString("x");
            var boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            request.ContentType = "multipart/form-data; boundary=" + boundary;
            var formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
            var buffer           = new byte[param.PostedFile.ContentLength];

            param.PostedFile.InputStream.Read(buffer, 0, buffer.Length);
            var strHeader = "Content-Disposition:application/x-www-form-urlencoded; name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n";

            strHeader = string.Format(strHeader,
                                      "filedata",
                                      param.PostedFile.FileName,
                                      param.PostedFile.ContentType);
            var byteHeader = ASCIIEncoding.ASCII.GetBytes(strHeader);

            try
            {
                using (var stream = request.GetRequestStream())
                {
                    if (param.PostParam != null)
                    {
                        var postParamString = "";
                        if (param.PostParam is string)
                        {
                            postParamString = param.PostParam.ToString();
                        }
                        else
                        {
                            postParamString = JSON.ToJSON(param.PostParam);
                        }
                        var bs = param.Encoding.GetBytes(postParamString);
                        stream.Write(bs, 0, bs.Length);
                    }
                    stream.Write(boundaryBytes, 0, boundaryBytes.Length);
                    stream.Write(byteHeader, 0, byteHeader.Length);
                    stream.Write(buffer, 0, buffer.Length);
                    var trailer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                    stream.Write(trailer, 0, trailer.Length);
                    stream.Close();
                }
                var response = (HttpWebResponse)request.GetResponse();
                var result   = "";
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    result = reader.ReadToEnd();
                }
                response.Close();
                return(result);
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }
        }
コード例 #3
0
 /// <summary>
 /// 获取响应流
 /// </summary>
 /// <param name="param"></param>
 /// <returns></returns>
 public static Stream RequestStream(HttpParam param)
 {
     #region 处理地址栏参数
     var getParamSb = new StringBuilder();
     if (param.GetParam != null)
     {
         if (param.GetParam is string)
         {
             getParamSb.Append(param.GetParam.ToString());
         }
         else
         {
             param.GetParam.GetType().GetProperties().ToList().ForEach(d =>
             {
                 getParamSb.AppendFormat("{0}={1}&", d.Name, d.GetValue(param.GetParam, null));
             });
         }
     }
     if (!string.IsNullOrWhiteSpace(getParamSb.ToString().TrimEnd('&')))
     {
         param.Url = string.Format("{0}?{1}", param.Url, getParamSb.ToString().TrimEnd('&'));
     }
     #endregion
     var r = WebRequest.Create(param.Url) as HttpWebRequest;
     if (!string.IsNullOrWhiteSpace(param.CertPath) && !string.IsNullOrWhiteSpace(param.CertPwd))
     {
         ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
         var cer = new X509Certificate2(param.CertPath, param.CertPwd, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
         r.ClientCertificates.Add(cer);
         #region 暂时不要的
         //ServicePointManager.Expect100Continue = true;
         //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
         //req.ProtocolVersion = HttpVersion.Version11;
         //req.UserAgent = SUserAgent;
         //req.KeepAlive = false;
         //var cookieContainer = new CookieContainer();
         //req.CookieContainer = cookieContainer;
         //req.Timeout = 1000 * 60;
         //req.Headers.Add("x-requested-with", "XMLHttpRequest");
         #endregion
     }
     r.Timeout         = param.TimeOut * 1000;
     r.UserAgent       = param.UserAgent;
     r.Method          = param.Method ?? "POST";
     r.Referer         = param.Referer;
     r.CookieContainer = param.CookieContainer;
     r.ContentType     = param.ContentType;
     if (param.PostParam != null)
     {
         var postParamString = "";
         if (param.PostParam is string)
         {
             postParamString = param.PostParam.ToString();
         }
         else
         {
             postParamString = JSON.ToJSON(param.PostParam);
         }
         var bs = param.Encoding.GetBytes(postParamString);
         r.ContentLength = bs.Length;
         using (var rs = r.GetRequestStream())
         {
             rs.Write(bs, 0, bs.Length);
         }
     }
     return(r.GetResponse().GetResponseStream());
 }