天天看點

C# HTTP POST AND GET json or xml

using System.Net;
        using System.Net.Cache;
        using System.IO;

        string HttpPost(string strUrl, string strPostData)
        {
            string result = string.Empty;
            try
            {
                HttpWebRequest request = HttpWebRequest.Create(strUrl) as HttpWebRequest;
                request.ContentType = "application/json";//or application/xml
                request.Method = "POST";
                request.Timeout = 5000;
                request.Accept = "*/*";
                request.KeepAlive = true;
                request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

                byte[] bytes = Encoding.UTF8.GetBytes(strPostData);
                request.ContentLength = bytes.Length;
                Stream writer = request.GetRequestStream();
                writer.Write(bytes, 0, bytes.Length);
                writer.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = reader.ReadToEnd();
                response.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(new Form { TopMost = true }, ex.Message);
            }

            return result;
        }