Beispiel #1
0
        public static string PostHttpRequest(string url, NameValueCollection col)
        {
            string output = null;
            StreamReader rs = null;

            try
            {
                string json_str = string.Empty;

                var client = new HttpClient();

                var postData = new List<KeyValuePair<string, string>>();
                if (col != null && col.Count > 0)
                {
                    IEnumerator myEnumerator = col.GetEnumerator();
                    foreach (String s in col.AllKeys)
                    {
                        postData.Add(new KeyValuePair<string, string>(s, col[s]));
                    }
                }

                HttpContent content = new FormUrlEncodedContent(postData);
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                var response = client.PostAsync(url, content).Result;
                if (!response.IsSuccessStatusCode)
                {
                    return null;
                }

                Stream res = response.Content.ReadAsStreamAsync().Result;
                rs = new StreamReader(res);
                output = rs.ReadToEnd();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            finally
            {
                if (rs != null)
                {
                    rs.Close();
                }
            }

            return output;
        }
Beispiel #2
0
        /// <summary>
        /// The get query string as dict.
        /// </summary>
        /// <param name="queryParameters">
        /// The query parameters.
        /// </param>
        /// <returns>
        /// The <see cref="IDictionary"/>.
        /// </returns>
        /// <exception cref="WebFaultException">
        /// </exception>
        public static IDictionary<string, string> GetQueryStringAsDict(NameValueCollection queryParameters)
        {
            IDictionary<string, string> paramsDict = new Dictionary<string, string>();
            var enumQ = queryParameters.GetEnumerator();
            while (enumQ.MoveNext())
            {
                var queryName = enumQ.Current.ToString();
                var queryValue = queryParameters[queryName];
                if (paramsDict.ContainsKey(queryName))
                {
                    Logger.Error("Duplicate parameters values is semantically error");
                    throw new WebFaultException(HttpStatusCode.BadRequest);
                }

                paramsDict.Add(queryName, queryValue);
            }

            return paramsDict;
        }
Beispiel #3
0
        public static string HttpGet(string url, NameValueCollection parameters)
        {
            if (parameters != null)
            {
                for (int i = 0; i < parameters.Count; i++)
                {
                    MessageBox.Show(parameters[i]);
                }

                url += "?";

                var e = parameters.GetEnumerator();
                while (e.MoveNext())
                {
                    //url += string.Format("{0}={1}&", e.Key, e.Value);
                }
            }

            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";

            WebResponse response = null;
            string result;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response;
            }
            finally
            {
                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    result = sr.ReadToEnd();
                }
            }

            return result;
        }
        protected Stream PrepareMultipartContent(string boundary, NameValueCollection data, Dictionary<string, Stream> files)
        {
            Stream stream = new MemoryStream();

            IEnumerator enumerator = data.GetEnumerator();

            enumerator.Reset();

            String template = Environment.NewLine + "--" + boundary + Environment.NewLine + "Content-Disposition: form-data; name=\"{0}\";" + Environment.NewLine + Environment.NewLine + "{1}";

            foreach (string key in data.Keys)
            {
                string param = string.Format(template, key, data[key]);
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(param);
                stream.Write(bytes, 0, bytes.Length);
            }

            template =
                Environment.NewLine + "--" + boundary + Environment.NewLine +
                "Content-Disposition: form-data; name=\"{0}\"; filename=\"{0}\"" + Environment.NewLine +
                "Content-Type: application/octet-stream" + Environment.NewLine + Environment.NewLine;

            foreach( KeyValuePair<string, Stream> file in files )
            {
                string param = string.Format(template, file.Key);
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(param);
                stream.Write(bytes, 0, bytes.Length);

                Stream fileStream = file.Value;
                fileStream.Position = 0;
                byte[] buffer = new byte[1024];
                int bytesRead = 0;

                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    stream.Write(buffer, 0, bytesRead);
                }
            }

            byte[] footBytes = System.Text.Encoding.UTF8.GetBytes(Environment.NewLine + "--" + boundary + "--");
            stream.Write(footBytes, 0, footBytes.Length);

            stream.Position = 0;

            return stream;
        }
        protected Stream PrepareContent(NameValueCollection data)
        {
            Stream stream = new MemoryStream();

            IEnumerator enumerator = data.GetEnumerator();

            enumerator.Reset();

            int count = data.Keys.Count;

            foreach (string key in data.Keys)
            {
                String param = Uri.EscapeDataString(key) + "=" + Uri.EscapeDataString(data[key]) + "&";
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(param);
                stream.Write(bytes, 0, bytes.Length);
            }

            if (stream.Length > 0)
            {
                //remove the "&" at the end
                stream.SetLength(stream.Length - 1);
            }

            stream.Position = 0;

            return stream;
        }
Beispiel #6
0
		/// <summary>
		/// Insert a record with multiple fields at the bottom of the hierarchy.
		/// </summary>
		/// <param name="xpath">The xml XPath query to get to the bottom node.</param>
		/// <param name="fields">The array of fields as field/value pairs.</param>
		/// <exception cref="System.ArgumentNullException">Thrown when an argument is null.</exception>
		/// <remarks>
		/// The "doc" variable must have a root node.  The path should not contain the root node.
		/// The path can contain only the node names or it can contain attributes in XPath query form.
		/// For example to insert an "Address" node at the bottom, the following is a valid xpath query
		///     xpath = "University[@Name='UT']/Student[@Id=12222]/Address"
		/// </remarks>
		public static void Insert(XmlDocument doc, string xpath, NameValueCollection nameValuePairs)
		{
			VerifyParameters(doc, xpath);
			if (nameValuePairs==null)
			{
				throw(new ArgumentNullException("fields cannot be null."));
			}

			XmlNode node=Insert(doc, xpath);

			System.Collections.IEnumerator iterator = nameValuePairs.GetEnumerator();
			string field, val;
			while (iterator.MoveNext())
			{
				field = iterator.Current.ToString();
				val = nameValuePairs[field];
				CreateAttribute(node, field, val);
			}
		}
Beispiel #7
0
        public static string PostHttpRequest(string url, NameValueCollection col, RequestType type, string contentType)
        {
            WeChatLogger.GetLogger().Info("PostHttpRequest.........");
            string output = null;
            StreamReader rs = null;
            try
            {
                string json_str = string.Empty;

                var client = new HttpClient();
                if (!string.IsNullOrEmpty(contentType))
                {
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
                }

                if (type == RequestType.POST)
                {
                    HttpContent content = null;
                    var postData = new List<KeyValuePair<string, string>>();
                    if (col != null && col.Count > 0)
                    {
                        IEnumerator myEnumerator = col.GetEnumerator();
                        if (contentType != null && contentType.ToLower() == "text/xml")
                        {
                            WeChatLogger.GetLogger().Info("post xml data...");
                            StringBuilder cBuilder = new StringBuilder();
                            cBuilder.Append("<xml>");
                            foreach (String s in col.AllKeys)
                            {
                                cBuilder.Append("<" + s + ">");
                                cBuilder.Append(col[s]);
                                cBuilder.Append("</" + s + ">");
                            }
                            cBuilder.Append("</xml>");
                            WeChatLogger.GetLogger().Info(cBuilder.ToString());
                            content = new StringContent(cBuilder.ToString());

                        }else
                        {
                            foreach (String s in col.AllKeys)
                            {
                                if(s!=null && col[s]!=null)
                                {
                                    postData.Add(new KeyValuePair<string, string>(s, col[s]));
                                }
                            }

                            content = new FormUrlEncodedContent(postData);
                        }
                    }

                    var response = client.PostAsync(url, content).Result;

                    if (!response.IsSuccessStatusCode)
                    {
                        return null;
                    }

                    Stream res = response.Content.ReadAsStreamAsync().Result;
                    //res = response.Content.ReadAsStreamAsync().Result;
                    if (contentType != "multipart/form-data")
                    {
                        rs = new StreamReader(res);
                        output = rs.ReadToEnd();
                    }
                }
                else if (type == RequestType.GET)
                {
                    StringBuilder urlParms = new StringBuilder();
                    if (col != null)
                    {
                        IEnumerator myEnumerator = col.GetEnumerator();
                        int count = 1;
                        foreach (String s in col.AllKeys)
                        {
                            urlParms.Append(s);
                            urlParms.Append("=");
                            urlParms.Append(col[s]);
                            if (count < (col.Count))
                            {
                                urlParms.Append("&");
                            }

                            count++;
                        }
                    }
                    string getUrl = url;
                    if (!string.IsNullOrEmpty(urlParms.ToString()))
                    {
                        getUrl += "?" + urlParms.ToString();
                    }
                    var response = client.GetAsync(getUrl).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        Stream res = response.Content.ReadAsStreamAsync().Result;
                        rs = new StreamReader(res);
                        output = rs.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                WeChatLogger.GetLogger().Error(ex);
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            finally
            {
                if (rs != null)
                {
                    rs.Close();
                }
            }
            WeChatLogger.GetLogger().Info("Post request done.");
            return output;
        }
        /// <summary> Loads the configuration.</summary>        
        public void LoadConfiguration()
        {
            try
            {
                properties = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("esapi");
                //properties = (NameValueCollection)System.Configuration.ConfigurationManager.OpenExeConfiguration(dllConfigFilePath).GetSection("esapi");
                resourceDirectory = properties.Get("ResourceDirectory");
                logger.LogSpecial("Loaded ESAPI properties from esapi/authentication", null);
            }
            catch (System.Exception e)
            {
                logger.LogSpecial("Can't load ESAPI properties from esapi/authentication", e);
                throw e;
            }

            logger.LogSpecial("  ========Master Configuration========", null);

            IEnumerator i = properties.GetEnumerator();
            while (i.MoveNext())
            {
                string key = (string)i.Current;
                logger.LogSpecial("  |   " + key + "=" + properties[(string)key], null);
            }
            logger.LogSpecial("  ========Master Configuration========", null);

            //cache regular expressions
            regexMap = new Hashtable();

            IEnumerator regexIterator = ValidationPatternNames;
            while (regexIterator.MoveNext())
            {
                string name = (string)regexIterator.Current;
                Regex regex = GetValidationPattern(name);
                if (name != null && regex != null)
                {
                    regexMap[name] = regex;
                }
            }
        }