Http请求GetPost封装

Posted by baicai on September 14, 2013
    public class HttpHelp
    {
        string boundary = "----------" + DateTime.Now.Ticks.ToString();
        public Dictionary<string, object> parameters = new Dictionary<string, object>();

        public async Task<Stream> Get(string url)
        {
            try
            {
                var request = (HttpWebRequest)WebRequest.Create(new Uri(url));
                request.Method = "GET";
                if (StaticData.Cookie != null && StaticData.Cookie != "")
                {
                    request.Headers["Cookie"] = StaticData.Cookie;
                }
                request.UserAgent = @"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)";
                var response = await request.GetResponseAsync();
                return response.GetResponseStream();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return null;
            }
        }

        public async Task<Stream> Post(string url)
        {
            try
            {
                var request = (HttpWebRequest)WebRequest.Create(new Uri(url));
                request.Method = "POST";
                if (StaticData.Cookie != null && StaticData.Cookie != "")
                {
                    request.Headers["Cookie"] = StaticData.Cookie;
                }
                request.UserAgent = @"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)";
                request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
                var stream = await request.GetRequestStreamAsync();

                writeMultipartObject(stream, parameters);

                stream.Close();
                var response = await request.GetResponseAsync();
                foreach (var key in response.Headers.AllKeys)
                {
                    if (key == "Set-Cookie")
                    {
                        StaticData.Cookie = response.Headers[key];
                    }
                }
                return response.GetResponseStream();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return null;
            }
        }

        public void writeMultipartObject(Stream stream, object data)
        {
            try
            {
                StreamWriter writer = new StreamWriter(stream);
                if (data != null)
                {
                    foreach (var entry in data as Dictionary<string, object>)
                    {
                        WriteEntry(writer, entry.Key, entry.Value);
                    }
                }
                writer.Write("--");
                writer.Write(boundary);
                writer.WriteLine("--");
                writer.Flush();
            }
            catch { }
        }

        private void WriteEntry(StreamWriter writer, string key, object value)
        {
            try
            {
                if (value != null)
                {
                    writer.Write("--");
                    writer.WriteLine(boundary);
                    if (value is byte[])
                    {
                        byte[] ba = value as byte[];

                        writer.WriteLine(@"Content-Disposition: form-data; name=""{0}""; filename=""{1}""", key, Guid.NewGuid().ToString() + ".jpg");
                        writer.WriteLine(@"Content-Type: image/jpeg");
                        writer.WriteLine(@"Content-Length: " + ba.Length);
                        writer.WriteLine();
                        writer.Flush();
                        Stream output = writer.BaseStream;

                        output.Write(ba, 0, ba.Length);
                        output.Flush();
                        writer.WriteLine();
                    }
                    else
                    {
                        writer.WriteLine(@"Content-Disposition: form-data; name=""{0}""", key);
                        writer.WriteLine();
                        writer.WriteLine(value.ToString());
                    }
                }
            }
            catch { }
        }
    }

WriteEntry中加入了post发送图片的支持