示例#1
0
        /// <summary>
        /// 使用Get方法获取字符串结果(加入Cookie)
        /// </summary>
        /// <param name="url"></param>
        /// <param name="cookieContainer"></param>
        /// <param name="encoding"></param>
        /// <param name="cer">证书,如果不需要则保留null</param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static string HttpGet(string url, CookieContainer cookieContainer = null,
                                     Encoding encoding = null, X509Certificate cer = null, int timeOut = TIME_OUT)
        {
            var handler = new HttpClientHandler();

            if (cookieContainer != null)
            {
                handler = new HttpClientHandler
                {
                    CookieContainer = cookieContainer,
                    UseCookies      = true,
                };
            }
            if (cer != null)
            {
                handler.ClientCertificates.Add(cer);
            }
            var httpClient = new HttpClient(handler)
            {
                Timeout = DayTimeHelper.CalculatingDifferenceSecond(timeOut)
            };
            var t = httpClient.GetStringAsync(url);

            t.Wait();
            return(t.Result);
        }
示例#2
0
        /// <summary>
        /// 使用Post方法获取字符串结果
        /// </summary>
        /// <param name="url"></param>
        /// <param name="cookieContainer"></param>
        /// <param name="postStream"></param>
        /// <param name="fileDictionary">需要上传的文件,Key:对应要上传的Name,Value:本地文件名</param>
        /// <param name="encoding"></param>
        /// <param name="cer">证书,如果不需要则保留null</param>
        /// <param name="timeOut"></param>
        /// <param name="checkValidationResult">验证服务器证书回调自动验证</param>
        /// <returns></returns>
        public static async Task <string> HttpPostAsync(string url, CookieContainer cookieContainer = null,
                                                        Stream postStream = null, Dictionary <string, string> fileDictionary = null, string refererUrl = null,
                                                        Encoding encoding = null, X509Certificate cer = null, int timeOut = TIME_OUT, bool checkValidationResult = false)
        {
            if (cookieContainer == null)
            {
                cookieContainer = new CookieContainer();
            }

            var handler = new HttpClientHandler {
                CookieContainer = cookieContainer
            };

            if (cer != null)
            {
                handler.ClientCertificates.Add(cer);
            }

            var client = new HttpClient(handler)
            {
                Timeout = DayTimeHelper.CalculatingDifferenceSecond(timeOut)
            };
            HttpContent hc = new StreamContent(postStream);

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xhtml+xml"));
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml", 0.9));
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/webp"));
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*", 0.8));
            //hc.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            hc.Headers.Add("UserAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36");
            hc.Headers.Add("Timeout", timeOut.ToString());
            hc.Headers.Add("KeepAlive", "true");

            #region 处理Form表单文件上传
            var formUploadFile = fileDictionary != null && fileDictionary.Count > 0;//是否用Form上传文件
            if (formUploadFile)
            {
                //通过表单上传文件
                postStream = postStream ?? new MemoryStream();

                var boundary = "----" + DateTime.Now.Ticks.ToString("x");
                //byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
                var fileFormdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
                var dataFormdataTemplate = "\r\n--" + boundary +
                                           "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
                foreach (var file in fileDictionary)
                {
                    try
                    {
                        var fileName = file.Value;
                        //准备文件流
                        using (var fileStream = FileHelper.GetFileStream(fileName))
                        {
                            string formdata = null;
                            formdata = fileStream != null?
                                       string.Format(fileFormdataTemplate, file.Key, /*fileName*/ Path.GetFileName(fileName)) :
                                           string.Format(dataFormdataTemplate, file.Key, file.Value);

                            //统一处理
                            var formdataBytes = Encoding.UTF8.GetBytes(postStream.Length == 0 ?
                                                                       formdata.Substring(2, formdata.Length - 2) :
                                                                       formdata);//第一行不需要换行

                            postStream.Write(formdataBytes, 0, formdataBytes.Length);

                            //写入文件
                            if (fileStream == null)
                            {
                                continue;
                            }
                            var buffer    = new byte[1024];
                            var bytesRead = 0;
                            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                            {
                                postStream.Write(buffer, 0, bytesRead);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Log(ex);
                        //throw ex;
                    }
                }
                //结尾
                var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
                postStream.Write(footer, 0, footer.Length);

                hc.Headers.ContentType =
                    new MediaTypeHeaderValue(string.Format("multipart/form-data; boundary={0}", boundary));
            }
            else
            {
                hc.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            }
            #endregion

            var r = await client.PostAsync(url, hc);

            return(await r.Content.ReadAsStringAsync());
        }