C#模拟http 发送post或get请求

转自: C#模拟http 发送post或get请求 

 1 private string HttpPost(string Url, string postDataStr)
 2         {
 3             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
 4             request.Method = "POST";
 5             request.ContentType = "application/x-www-form-urlencoded";
 6             request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
 7             request.CookieContainer = cookie;
 8             Stream myRequestStream = request.GetRequestStream();
 9             StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
10             myStreamWriter.Write(postDataStr);
11             myStreamWriter.Close();
12  
13             HttpWebResponse response = (HttpWebResponse)request.GetResponse();
14  
15             response.Cookies = cookie.GetCookies(response.ResponseUri);
16             Stream myResponseStream = response.GetResponseStream();
17             StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
18             string retString = myStreamReader.ReadToEnd();
19             myStreamReader.Close();
20             myResponseStream.Close();
21  
22             return retString;
23         }
24  
25         public string HttpGet(string Url, string postDataStr)
26         {
27             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
28             request.Method = "GET";
29             request.ContentType = "text/html;charset=UTF-8";
30  
31             HttpWebResponse response = (HttpWebResponse)request.GetResponse();
32             Stream myResponseStream = response.GetResponseStream();
33             StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
34             string retString = myStreamReader.ReadToEnd();
35             myStreamReader.Close();
36             myResponseStream.Close();
37  
38             return retString;
39         }

在post的时候有时也用的到cookie,像登录163发邮件时候就需要发送cookie,所以在外部一个cookie属性随时保存 CookieContainer cookie = new CookieContainer();

!注意:有时候请求会重定向,但我们就需要从重定向url获取东西,像QQ登录成功后获取sid,但上面的会自动根据重定向地址跳转。我们可以用:
request.AllowAutoRedirect = false;设置重定向禁用,你就可以从headers的Location属性中获取重定向地址

 

Post另一实现:

post 调用时传参,如:

string url = "http://www.baidu.com/";
            string result = string.Empty;

            string param = string.Format("WechatOpenID={0}&Content={1}", webchatOpenID, content);
            result = HttpPostData(url, param);

 

 

public string HttpPostData(string url, string param)
        {
            var result = string.Empty;
            //注意提交的编码 这边是需要改变的 这边默认的是Default:系统当前编码
            byte[] postData = Encoding.UTF8.GetBytes(param);

            // 设置提交的相关参数 
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            Encoding myEncoding = Encoding.UTF8;
            request.Method = "POST";
            request.KeepAlive = false;
            request.AllowAutoRedirect = true;
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR  3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
            request.ContentLength = postData.Length;

            // 提交请求数据 
            System.IO.Stream outputStream = request.GetRequestStream();
            outputStream.Write(postData, 0, postData.Length);
            outputStream.Close();

            HttpWebResponse response;
            Stream responseStream;
            StreamReader reader;
            string srcString;
            response = request.GetResponse() as HttpWebResponse;
            responseStream = response.GetResponseStream();
            reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));
            srcString = reader.ReadToEnd();
            result = srcString;   //返回值赋值
            reader.Close();

            return result;
        }

 

Post传输图片等时的代码示例:

Post多张图片和其他参数时,用此方法进行调用,调用方法如:

//imgDic是图片接收名称如media,图片本地完整路径或网络完整路径的键值对的集合

imgDesc是图片信息参数及其他参数的集合,图片信息如media1,media2,media3等,这个图片接收名字是由接收方确定的

注意:

FileStream只能用于本地完整路径,如C/xx.jpg等,如果是网路图片则无法使用它。

推荐使用

WebClient wc = new WebClient();
            byte[] buffer = wc.DownloadData(filePath);
            memStream.Write(buffer, 0, buffer.Length);

这种方式,这个类无论是网路图片还是本地图片都可以使用,但路径中要用/,而不是\,否则会出现不支持URI的错误。

if (openIDList != null && openIDList.Any() && imgDesc != null)
            {
                Dictionary<string, string> imgDic = new Dictionary<string, string>();
                foreach (var item in imgDesc)
                {
                    imgDic.Add(item.name, item.path);
                }

                NameValueCollection col = new NameValueCollection();
                col.Add("imgDesc", Newtonsoft.Json.JsonConvert.SerializeObject(imgDesc));
                col.Add("open_ids", string.Join(",", openIDList));
                result = HttpPostData(url, 60000, imgDic, col);
            }

 

private static string HttpPostData(string url, int timeOut, Dictionary<string, string> imgDic, NameValueCollection stringDict)
        {
            LogEntry entry = new LogEntry("发送图片开始-HttpPostData -- " + stringDict["open_ids"], 1);
            LogStub.Log(entry);

            var firstImg = imgDic.FirstOrDefault();
            string fileKeyName = firstImg.Key;
            string filePath = firstImg.Value;

            string responseContent;
            var memStream = new MemoryStream();
            var webRequest = (HttpWebRequest)WebRequest.Create(url);
            // 边界符
            var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
            // 边界符
            var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
            //var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            
            // 最后的结束符
            var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");

            // 设置属性
            webRequest.Method = "POST";
            webRequest.Timeout = timeOut;
            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

            // 写入文件
            const string filePartHeader =
                "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
                 "Content-Type: application/octet-stream\r\n\r\n";
            var header = string.Format(filePartHeader, fileKeyName, filePath);
            var headerbytes = Encoding.UTF8.GetBytes(header);

            memStream.Write(beginBoundary, 0, beginBoundary.Length);
            memStream.Write(headerbytes, 0, headerbytes.Length);

            //var buffer = new byte[1024];
            //int bytesRead; // =0

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

            WebClient wc = new WebClient();
            byte[] buffer = wc.DownloadData(filePath);
            memStream.Write(buffer, 0, buffer.Length);

            //第二章图片
            //memStream.Write(beginBoundary, 0, beginBoundary.Length);


            //var aaa = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
            //memStream.Write(aaa, 0, aaa.Length);

            string imgName = string.Empty;
            string imgPath = string.Empty;
            foreach (var img in imgDic.Where(p => p.Key != fileKeyName))
            {
                imgName = img.Key;
                imgPath = img.Value;

                string nxetFileFormat = "\r\n--" + boundary + "\r\n" + filePartHeader;

                header = string.Format(nxetFileFormat, imgName, imgPath);
                headerbytes = Encoding.UTF8.GetBytes(header);

                memStream.Write(headerbytes, 0, headerbytes.Length);
                //fileStream = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
                //while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                //{
                //    memStream.Write(buffer, 0, bytesRead);
                //}

                buffer = wc.DownloadData(imgPath);
                memStream.Write(buffer, 0, buffer.Length);
            }

            // 写入字符串的Key
            var stringKeyHeader = "\r\n--" + boundary +
                                   "\r\nContent-Disposition: form-data; name=\"{0}\"" +
                                   "\r\n\r\n{1}\r\n";

            foreach (byte[] formitembytes in from string key in stringDict.Keys
                                             select string.Format(stringKeyHeader, key, stringDict[key])
                                                 into formitem
                                                 select Encoding.UTF8.GetBytes(formitem))
            {
                memStream.Write(formitembytes, 0, formitembytes.Length);
            }

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

            webRequest.ContentLength = memStream.Length;

            var requestStream = webRequest.GetRequestStream();

            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();

            var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();

            using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(),
                                                            Encoding.GetEncoding("utf-8")))
            {
                responseContent = httpStreamReader.ReadToEnd();
            }

            fileStream.Close();
            httpWebResponse.Close();
            webRequest.Abort();

            entry = new LogEntry("发送图片结束-HttpPostData -- " + responseContent, 1);
            LogStub.Log(entry);

            return responseContent;
        }

 

 

 

 

单行图片调用以下方法时,如:

NameValueCollection col = new NameValueCollection();
                //col.Add("media", filePath);
                col.Add("title", title);
                col.Add("content", content);
                col.Add("open_ids", string.Join(",", openIDList));

                result = HttpPostData(url, 60000, "media", filePath, col);

filePath是客户端的图片完整路径,

media是服务端接受图片的参数,这个要看接收端接收图片的参数名,注意此方法是单张图片的post调用

private static string HttpPostData(string url, int timeOut, string fileKeyName,
                                    string filePath, NameValueCollection stringDict)
        {
            string responseContent;
            var memStream = new MemoryStream();
            var webRequest = (HttpWebRequest)WebRequest.Create(url);
            // 边界符
            var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
            // 边界符
            var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            // 最后的结束符
            var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");

            // 设置属性
            webRequest.Method = "POST";
            webRequest.Timeout = timeOut;
            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

            // 写入文件
            const string filePartHeader =
                "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
                 "Content-Type: application/octet-stream\r\n\r\n";
            var header = string.Format(filePartHeader, fileKeyName, filePath);
            var headerbytes = Encoding.UTF8.GetBytes(header);

            memStream.Write(beginBoundary, 0, beginBoundary.Length);
            memStream.Write(headerbytes, 0, headerbytes.Length);

            var buffer = new byte[1024];
            int bytesRead; // =0

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

            // 写入字符串的Key
            var stringKeyHeader = "\r\n--" + boundary +
                                   "\r\nContent-Disposition: form-data; name=\"{0}\"" +
                                   "\r\n\r\n{1}\r\n";

            foreach (byte[] formitembytes in from string key in stringDict.Keys
                                             select string.Format(stringKeyHeader, key, stringDict[key])
                                                 into formitem
                                                 select Encoding.UTF8.GetBytes(formitem))
            {
                memStream.Write(formitembytes, 0, formitembytes.Length);
            }

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

            webRequest.ContentLength = memStream.Length;

            var requestStream = webRequest.GetRequestStream();

            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();

            var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();

            using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(),
                                                            Encoding.GetEncoding("utf-8")))
            {
                responseContent = httpStreamReader.ReadToEnd();
            }

            fileStream.Close();
            httpWebResponse.Close();
            webRequest.Abort();

            return responseContent;
        }

 

 

 原理简介及简单实现:

WebRequest request = WebRequest.Create("http://www.baidu.com/");//为指定的 URI 方案初始化新的 System.Net.WebRequest 实例
        request.UseDefaultCredentials = false;//获取或设置一个 System.Boolean 值,该值控制 System.Net.CredentialCache.DefaultCredentials
        WebResponse response = request.GetResponse();//返回对 Internet 请求的响应。
        Stream resStream = response.GetResponseStream();//返回从 Internet 资源返回数据流
        StreamReader sr = new StreamReader(resStream, System.Text.Encoding.Default);//实例华一个流的读写器
        ContentHtml.Text = sr.ReadToEnd();//这就是百度首页的HTML哦 ,字符串形式的流的其余部分(从当前位置到末尾)。如果当前位置位于流的末尾,则返回空字符串 ("")
        resStream.Close();//关闭当前流并释放与之关联的所有资源
        sr.Close(); //关闭 System.IO.StreamReader 对象和基础流,并释放与读取器关联的所有系统资源

 

 

HttpWebRequest 和 HttpWebResponse 的应用

 
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(addr);
// Downloads the XML file from the specified server.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.IO.StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("gb2312"));
Console.Write(sr.ReadToEnd());
sr.Close();
response.Close();


1.获取http地址上的图片
http://www.cnblogs.com/fooo/archive/2007/06/28/798335.html
HttpWebResponse resp;
        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://www.csdn.net/Images/logo_csdn.gif");
        req.Timeout = 150000;
        resp = (HttpWebResponse)req.GetResponse();
        System.Drawing.Image img;
        img = new System.Drawing.Bitmap(resp.GetResponseStream());

2.

HttpWebRequest&HttpWebResponse Headers

介绍

这里简要介绍如何使用HttpWebRequest&HttpWebResponse两个对象与HTTP服务器进行直接交互的过程.HttpWebRequest类对WebRequest中定义的属性和方法提供支持,在使用HttpWebRequest对象向HTTP服务器发起请求时请不要使用HttpWebRequest对象的构造函数,而应该使用WebRequest.Create()方法来初始化新的HttpWebRequest对象.如果统一资源标识符方案是"http://"或"https://"时,Create()则返回HttpWebResponse对象.

代码

首先,我们需要创建一个新的HttpWebRequest对象,代码如下:

HttpWebRequest myrequest = (HttpWebRequest)WebRequest.Create(new Uri("urlstring"));

注意:上文中已经提到过不要使用HttpWebRequest的构造函数来创建对象;使用WebRequest.Create()方法初始化HttpWebRequest对象时应该对其进行类型转换.

接下来可以对新初始化的对象进行简单操作,比如可以设置它的标头属性,
下表列出了由属性或方法设置或由系统设置的标头:



标头

设置方法

Accept                 由Accept属性设置                
Connection                     由Connection属性和KeepAlive属性设置                    
Content-Length                         由ContentLength属性设置                        
Content-Type                             由ContentType属性设置                            
Expect                                 由Expect属性设置                                
Date                                     由系统设置为当前日期                                    
Host                                         由系统设置为当前主机信息                                        
If-Modified-Since                                             由IfModifiedSince属性设置                                            
Range                                                 由Range属性设置                                                
Transfer-Encoding                                                     由TransferEncoding属性设置                                                    
Referer                                                         由Referer属性设置                                                        
User-Agent                                                            

由UserAgent属性设置

 


注意:HttpWebRequest自动注册.使用以"http://"或"https://"开头的URL之前,不需要调用RegisterPrefix方法来注册                                                

System.Net.HttpWebRequest选自:
MSDN:ms-help://MS.MSDNQTR.v80.chs/MS.MSDN.v80/MS.NETDEVFX.v20.chs/cpref10/html/T_System_Net_HttpWebRequest.htm
                                                

在完成对服务器的请求之后,我们需要获取从服务器中返回的信息,正如前面提到过的,使用HttpWebResponse类,具体做法参照如下代码:                                                

HttpWebResponse myresponse = (HttpWebResponse)myrequest.GetResponse();                                                

同样这里我们需要使用HttpWebResponse进行类型转换.到这里,我们已经成功的获得服务器返回的信息,一个myresponse对象,我们可以利用它来获得更多详细的信息,比如从服务器返回的Headers标头,还有其他的有用信息.而在此我们只给您列出如何获得来自服务器响应的Headers标头信息.我们的具体方法是这样的:                                                

        #region GetHeaders                                                

        public static WebHeaderCollection GetHeaders(Uri uri)                                                

        {                                                

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);                                                

            // 省略部分代码......                                                

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();                                                

            // 省略部分代码......                                                

            return response.Headers;                                                

        }                                                

        #endregion                                                

 

下面就是提供的main()函数:                                                

        // The app entry point                                                

        public static void Main(string[] args)                                                

        {                                                

            WebHeaderCollection headers = GetHeaders(new Uri("http://www.listim.net"));                                                

            string[] headkeys = headers.AllKeys;                                                

            Console.WriteLine("{0,-30}{1}""Name""Value");                                                

            Console.WriteLine("--------------------------------");                                                

            foreach (string s in headkeys)                                                

            {                                                

                Console.WriteLine("{0,-30}{1}", s, headers[s]);                                                

            }                                                

        }

 

 

 

另一种实现方式:

/// <summary>
        /// Post data到url
        /// </summary>
        /// <param name="data">要post的数据</param>
        /// <param name="url">目标url</param>
        /// <returns>服务器响应</returns>
        static string PostDataToUrl(string data, string url)
        {
            Encoding encoding = Encoding.GetEncoding(sRequestEncoding);
            byte[] bytesToPost = encoding.GetBytes(data);
            return PostDataToUrl(bytesToPost, url);
        }

        /// <summary>
        /// Post data到url
        /// </summary>
        /// <param name="data">要post的数据</param>
        /// <param name="url">目标url</param>
        /// <returns>服务器响应</returns>
        static string PostDataToUrl(byte[] data, string url)
        {
            #region 创建httpWebRequest对象
            WebRequest webRequest = WebRequest.Create(url);
            HttpWebRequest httpRequest = webRequest as HttpWebRequest;
            if (httpRequest == null)
            {
                throw new ApplicationException(
                string.Format("Invalid url string: {0}", url)
                );
            }
            #endregion

            #region 填充httpWebRequest的基本信息
            httpRequest.UserAgent = sUserAgent;
            httpRequest.ContentType = sContentType;
            httpRequest.Method = "POST";
            #endregion

            #region 填充要post的内容
            httpRequest.ContentLength = data.Length;
            Stream requestStream = httpRequest.GetRequestStream();
            requestStream.Write(data, 0, data.Length);
            requestStream.Close();
            #endregion


            #region 发送post请求到服务器并读取服务器返回信息
            Stream responseStream;
            try
            {
                responseStream = httpRequest.GetResponse().GetResponseStream();
            }
            catch (Exception e)
            {
                // log error
                Console.WriteLine(
                string.Format("POST操作发生异常:{0}", e.Message)
                );
                throw e;
            }
            #endregion

            #region 读取服务器返回信息
            string stringResponse = string.Empty;
            using (StreamReader responseReader =
            new StreamReader(responseStream, Encoding.GetEncoding(sResponseEncoding)))
            {
                stringResponse = responseReader.ReadToEnd();
            }
            responseStream.Close();
            #endregion
            return stringResponse;
        }

调用时:

string param = string.Format("time={0}&oid={1}&order={2}&name={3}&area={4}&point={5}&amount={6}&return={7}&hash={8}&version={9}", Time, Oid, OrderID, LoginName, Area, Point, Amount, ReturnUrl, HashMoli, Version);

string result = PostDataToUrl(param, PostUrl);

 

 

还有一种实现的例子:

 

使用httpwebrequest Post数据到网站

 
怎样通过HttpWebRequest 发送 POST 请求到一个网页服务器?例如编写个程序实现自动用户登录,自动提交表单数据到网站等。
假如某个页面有个如下的表单(Form):
<form name="form1" action="http://www.here.com/login.asp" method="post">
  <input type="text" name="userid" value="">
  <input type="password" name="password" value="">
< /form>
    
从表单可看到表单有两个表单域,一个是userid另一个是password,所以以POST形式提交的数据应该包含有这两项。
其中POST的数据格式为:
表单域名称1=值1&表单域名称2=值2&表单域名称3=值3……
要注意的是“值”必须是经过HTMLEncode的,即不能包含“<>=&”这些符号。

本例子要提交的数据应该是:
userid=value1&password=value2

用C#写提交程序:

  string strId = "guest";
  string strPassword= "123456";

  ASCIIEncoding encoding=new ASCIIEncoding();
  string postData="userid="+strId;
  postData += ("&password="+strPassword);

  byte[] data = encoding.GetBytes(postData);

  // Prepare web request...
  HttpWebRequest myRequest =
   (HttpWebRequest)WebRequest.Create("http://www.here.com/login.asp");

  myRequest.Method = "POST";
  myRequest.ContentType="application/x-www-form-urlencoded";
  myRequest.ContentLength = data.Length;
  Stream newStream=myRequest.GetRequestStream();

  // Send the data.
  newStream.Write(data,0,data.Length);
  newStream.Close();

  // Get response
  HttpWebResponse myResponse=(HttpWebResponse)myRequest.GetResponse();
  StreamReader reader = new StreamReader(response.GetResponseStream(),Encoding.Default);
  string content = reader.ReadToEnd();
  Console.WriteLine(content);
posted @ 2017-06-22 10:55  Aaronguo  阅读(52765)  评论(0编辑  收藏  举报