Exemplo n.º 1
0
        public static string SendByGet(string url, Dictionary <string, string> formDataDict, string secretKey)
        {
            Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

            formDataDict.Add("app_sign", Md5Util.getSignature(formDataDict, secretKey));
            StringBuilder sb = new StringBuilder();

            foreach (var key in formDataDict)
            {
                if (sb.ToString() != "")
                {
                    sb.Append("&");
                }
                sb.AppendFormat("{0}={1}", key.Key, key.Value);
            }

            url += "?" + sb.ToString();
            HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url);

            CookieContainer myCookieContainer = GetCookies();

            webRequest.CookieContainer = myCookieContainer;
            webRequest.KeepAlive       = false;

            webRequest.Method = "GET";
            //处理响应信息
            using (WebResponse myResp = webRequest.GetResponse())
            {
                Stream       ReceiveStream = myResp.GetResponseStream();
                StreamReader readStream    = new StreamReader(ReceiveStream, encode);
                Char[]       read          = new Char[256];
                int          count         = readStream.Read(read, 0, 256);
                string       responseData  = null;
                while (count > 0)
                {
                    responseData += new String(read, 0, count);
                    count         = readStream.Read(read, 0, 256);
                }
                readStream.Close();
                //cookie操作
                var response = (HttpWebResponse)myResp;
                try
                {
                    for (int i = 0; i < response.Cookies.Count; i++)
                    {
                        if (HttpContext.Current.Response != null && response.Cookies[i].Value != null && response.Cookies[i].Value != "" &&
                            response.Cookies[i].Name != null && response.Cookies[i].Name != "")
                        {
                            System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath("/logs/error.txt"), "\r\n get-method: " + i.ToString() + " " + response.Cookies[i].Name + "\r\n");
                            System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath("/logs/error.txt"), "\r\n get-method: " + i.ToString() + " " + response.Cookies[i].Value + "\r\n");
                            if (HttpContext.Current.Response.Cookies[response.Cookies[i].Name].Value.Contains(","))
                            {
                                continue;
                            }
                            HttpContext.Current.Response.Cookies[response.Cookies[i].Name].Value = response.Cookies[i].Value;
                        }
                        //cookiestr += response.Cookies[i].Name + "=" + response.Cookies[i].Value.ToString()+"\r\n";
                    }
                }
                catch (Exception ee)
                {
                    System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath("/logs/error.txt"), "\r\n get-method: cookies set error: " + ee.Message + ee.StackTrace + "\r\n");
                }

                response.Close();
                response = null;
                myResp.Close();
                //返回响应信息
                return(responseData);
            }
        }
Exemplo n.º 2
0
        /**
         * 支持参数和附件的post请求
         *
         **/
        public static string SendByPost(string url, Dictionary <string, string> formDataDict, string[] filePathArray, string secretKey)
        {
            System.GC.Collect();
            System.Net.ServicePointManager.DefaultConnectionLimit = 512;
            try
            {
                Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

                // 边界符
                var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
                // 最后的结束符
                var endBoundary = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

                CookieContainer myCookieContainer = GetCookies();
                HttpWebRequest  webRequest        = (HttpWebRequest)HttpWebRequest.Create(url);
                webRequest.CookieContainer = myCookieContainer;

                webRequest.Timeout = 10000;
                //webRequest.KeepAlive = false;
                webRequest.Method      = "POST";
                webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

                var memStream = new MemoryStream();

                //添加文件信息
                addFileInfo(memStream, filePathArray, boundary);

                //生成sign并设置到参数里面
                formDataDict.Add("app_sign", Md5Util.getSignature(formDataDict, secretKey));
                //添加form参数信息
                addFormData(memStream, formDataDict, boundary);

                // 写入最后的结束边界符
                memStream.Write(endBoundary, 0, endBoundary.Length);

                //webRequest.ContentLength = memStream.Length;  //系统会自动计算
                //这个在Post的时候,一定要加上,如果服务器返回错误,他还会继续再去请求,不会使用之前的错误数据,做返回数据
                webRequest.ServicePoint.Expect100Continue = false;

                HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                webRequest.CachePolicy = noCachePolicy;

                var requestStream = webRequest.GetRequestStream();

                //将post的信息设置到请求流里面
                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();

                string responseData = "";
                //处理响应信息
                //using (WebResponse myResp = webRequest.GetResponse())
                using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
                {
                    //var response = (HttpWebResponse)myResp;
                    if (response.StatusCode == HttpStatusCode.RequestTimeout)
                    {
                        System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath("/logs/error.txt"), "\r\n [请求超时]\r\n");
                        Thread.Sleep(1000);
                        return(null);
                    }

                    Stream       ReceiveStream = response.GetResponseStream();
                    StreamReader readStream    = new StreamReader(ReceiveStream, encode);
                    Char[]       read          = new Char[256];
                    int          count         = readStream.Read(read, 0, 256);

                    while (count > 0)
                    {
                        responseData += new String(read, 0, count);
                        count         = readStream.Read(read, 0, 256);
                    }
                    readStream.Close();

                    //cookie操作


                    //string cookiestr = "cookiestr:";    //debug
                    try
                    {
                        //System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath("/logs/error.txt"), "\r\n cookies总数:" + response.Cookies.Count.ToString() + "\r\n");

                        for (int i = 0; i < response.Cookies.Count; i++)
                        {
                            if (response.Cookies[i].Name == "ASP.NET_SessionId")
                            {
                                continue;
                            }
                            if (HttpContext.Current.Response != null && response.Cookies[i].Value != null && response.Cookies[i].Value != "" &&
                                response.Cookies[i].Name != null && response.Cookies[i].Name != "")
                            {
                                //System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath("/logs/error.txt"), "\r\n " + i.ToString() + " name:" + response.Cookies[i].Name + "\r\n");

                                HttpContext.Current.Response.Cookies[response.Cookies[i].Name].Value = response.Cookies[i].Value;
                                //System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath("/logs/error.txt"), "\r\n " + i.ToString() + " value:" + response.Cookies[i].Value + "\r\n");
                            }
                        }
                    }
                    catch (Exception ee)
                    {
                        System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath("/logs/error.txt"), "\r\n cookies set error: " + ee.Message + ee.StackTrace + "\r\n");
                    }
                    //debug
                    //System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath("/logs/" + DateTime.Now.ToString("yyHHmmhhMMss") + ".txt"), cookiestr);
                    //
                    response.Close();
                    //返回响应信息
                }
                webRequest.Abort();
                webRequest = null;
                return(responseData);
            }
            catch (Exception e)
            {
                System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath("/logs/error.txt"), e.Message + e.StackTrace + e.Source + e.TargetSite);
                var json = new Json("10001", "访问API时发生错误,EROR:175 " + e.Message + e.TargetSite);
                return(json.ToString());
            }
        }