博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何获取和发送Http请求和相应
阅读量:6265 次
发布时间:2019-06-22

本文共 5001 字,大约阅读时间需要 16 分钟。

首先发送get request,从response中获取cookie:

Get:

string address = string.Empty;            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(address);            // Two ways to  set the authorization:             //Method 1:            //myRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("domainName/name" + ":" + "psw"));            //Method 2:            NetworkCredential cred = CredentialCache.DefaultCredentials as NetworkCredential;            myRequest.Credentials = cred;            myRequest.Method = "GET";            myRequest.Accept = "image/jpeg, image/gif, image/pjpeg, application/x-ms-application, application/xaml+xml, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";            myRequest.Headers.Set("Accept-Language", "en-US");            myRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)";            myRequest.Headers.Set("Accept-Encoding", "gzip, deflate");            myRequest.Host = "HostName";            myRequest.CookieContainer = new CookieContainer();            myRequest.CookieContainer.Add(new Uri("http://localhost"),new Cookie());                   // Resolve the issue of Expect: 100-continue            // eg: http://blogs.msdn.com/b/fiddler/archive/2011/11/05/http-expect-continue-delays-transmitting-post-bodies-by-up-to-350-milliseconds.aspx            myRequest.ServicePoint.Expect100Continue = false;                        string cookieString = string.Empty;            //string             using (HttpWebResponse webResponse = myRequest.GetResponse() as HttpWebResponse)            {                // Read response head info.                cookieString = webResponse.Headers["Set-Cookie"];                               // Keep the cookie and use when the next send request                myRequest.CookieContainer = new CookieContainer();                myRequest.CookieContainer.SetCookies(new Uri(address), cookieString);                              string resultstring = webResponse.GetResponseString();            }

Extension method:

public static class HttpWebResponseExtension    {        public static string GetResponseString(this HttpWebResponse res)        {            string resultstring = null;            using (Stream receiveStream = res.GetResponseStream())            {                using (StreamReader sr = new StreamReader(receiveStream))                {                    resultstring = sr.ReadToEnd();                }            }            Console.WriteLine("Get Response String Completed.");            return resultstring;        }    }

Post:

private static void PostMethod(string address, CookieContainer container, Encoding mye, string bodyContent, string cookieString)        {            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(address);            byte[] arrB = mye.GetBytes(bodyContent);            myReq.Method = "POST";            myReq.Accept = "image/jpeg, image/gif, image/pjpeg, application/x-ms-application, application/xaml+xml, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";            myReq.ContentLength = arrB.Length;            myReq.Referer = "http://localHost";            myReq.Host = "HostName";            myReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)";            myReq.ContentLength = bodyContent.Length;                      NetworkCredential cred = CredentialCache.DefaultCredentials as NetworkCredential;            myReq.Credentials = cred;            myReq.ContentType = "multipart/form-data; boundary=---------------------------1223334444555";            myReq.Headers.Set("Accept-Encoding", "gzip, deflate");            myReq.Headers.Set("Accept-Language", "en-US");            myReq.Headers.Set("Pragma", "no-cache");            myReq.KeepAlive = true;            myReq.CookieContainer = new CookieContainer();            myReq.CookieContainer.SetCookies(new Uri(address), cookieString);            myReq.ServicePoint.Expect100Continue = false;                     string resultstring = string.Empty;            string fileName = string.Empty;            try            {                using (HttpWebResponse resPost = myReq.GetResponse() as HttpWebResponse)                {                    fileName = resPost.Headers["Content-disposition"];                    int index = fileName.IndexOf("filename=");                    fileName = fileName.Substring(index + 9);                    resultstring = resPost.GetResponseString();                }            }            catch (WebException err)            {                using (HttpWebResponse resErr = err.Response as HttpWebResponse)                {                    resultstring = resErr.GetResponseString();                }            }            string path = Path.Combine("D:\\FolderName", fileName);            File.WriteAllText(path, resultstring);              }

 

 

转载地址:http://qvdpa.baihongyu.com/

你可能感兴趣的文章
Java中Lambda表达式的使用
查看>>
Spring Cloud Sleuth超详细实战
查看>>
如何让windows服务器IIS支持.apk/.ipa文件下载
查看>>
Django import / export实现数据库导入导出
查看>>
php内核分析(八)-zend_compile
查看>>
【转】【高斯】高斯模糊算法[2]
查看>>
教程-Close、Halt、terminate、ExitProcess的区别
查看>>
IOC和DI
查看>>
Entity Framework 4 & 4.1
查看>>
统计在线人数
查看>>
HDU 2282 Chocolate
查看>>
jquery ui datepicker 只能选今天以后的日期
查看>>
控件:Gallery --- 3.(实现图片切换)
查看>>
Struts标签---logic:Iterate使用方法
查看>>
HDOJ-1102 Constructing Roads
查看>>
两分钟彻底让你明白Android Activity生命周期(图文)!
查看>>
关于KMP算法
查看>>
当C++遇到iOS应用开发---SQLITE篇
查看>>
Lucene
查看>>
html input readonly 和 disable的区别
查看>>