WinNetAPIDemo获得HTML页面

WinInet.cs文件:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace WinNetAPIDemo
{
    public class WinInet
    {
        public static int FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
        public static short INTERNET_DEFAULT_HTTP_PORT = 80;
        public static short INTERNET_SERVICE_HTTP = 3;
        public static uint HTTP_ADDREQ_FLAG_REPLACE = 0x80000000;
        public static uint HTTP_ADDREQ_FLAG_ADD = 0x20000000;
        public static int HTTP_QUERY_CONTENT_LENGTH = 5;
        public const int INTERNET_OPEN_TYPE_PRECONFIG = 0; 
        public const int INTERNET_OPEN_TYPE_DIRECT = 1;
        public const int INTERNET_OPEN_TYPE_PROXY = 3;
        public const uint INTERNET_FLAG_RELOAD = 0x80000000;
        [DllImport("wininet.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern IntPtr InternetOpen(string lpszAgent, int dwAccessType, string lpszProxyName, string lpszProxyBypass, int dwFlags);
        [DllImport("wininet.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool InternetCloseHandle(IntPtr hInternet);
        [DllImport("wininet.dll", SetLastError = true)]
        public static extern IntPtr InternetOpenUrl(IntPtr hOpen, string sUrl, string sHeaders, int lLength, uint lFlags, int lContext);
        [DllImport("wininet.dll", EntryPoint = "InternetReadFile", SetLastError = true)]
        public static extern bool InternetReadFile(IntPtr hFileFind, byte[] pBuffer, uint nBytesToRead, ref uint nBytesRead);
        [DllImport("wininet.dll", SetLastError = true)]
        public static extern bool HttpAddRequestHeaders(IntPtr hRequest, [MarshalAs(UnmanagedType.LPWStr)] string pwszHeaders, int dwHeadersLength, uint dwModifiers);
        [DllImport("wininet.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern IntPtr InternetConnect(IntPtr hInternet, string lpszServerName, short nServerPort, string lpszUsername, string lpszPassword, int dwService, int dwFlags, IntPtr dwContext);
        [DllImport("WinInet.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern IntPtr HttpOpenRequest(IntPtr hConnect, string lpszVerb, string lpszObjectName, string lpszVersion, string lpszReferrer, long lpszAcceptTypes, UInt32 dwFlags, IntPtr dwContext);
        [DllImport("wininet.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern bool HttpSendRequest(IntPtr hRequest, string lpszHeaders, int dwHeadersLength, string lpOptional, int dwOptionalLength);
        [DllImport("wininet.dll", SetLastError = true)]
        public static extern bool HttpQueryInfo(IntPtr hInternet, int dwInfoLevel, ref long lpBuffer, ref long lpdwBufferLength, ref long lpdwIndex);
    }
}
MyHttp.cs文件
using System;
using System.Text;
using System.Net;
using System.IO;
namespace WinNetAPIDemo
{
    public class MyHttp
    {
        public static string GetHtml_HttpWebResponse(string url, string method, string postData)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = method;
            request.Timeout = 20000;
            request.KeepAlive = true;
            request.AllowAutoRedirect = false;
            request.AllowWriteStreamBuffering = true;
            request.ContentType = "application/x-www-form-urlencoded";
            HttpWebResponse webresponse = null;
            try
            {
                if (postData.Length > 0)
                {
                    byte[] loginDataBytes = System.Text.Encoding.GetEncoding("utf-8").GetBytes(postData);
                    Stream stream = request.GetRequestStream(); stream.Write(loginDataBytes, 0, loginDataBytes.Length); stream.Close();
                } webresponse = request.GetResponse() as HttpWebResponse; if (webresponse != null)
                {
                    StreamReader reader = new StreamReader(webresponse.GetResponseStream(), Encoding.GetEncoding("GB2312")); string strHTML = reader.ReadToEnd();
                    if (reader != null) { reader.Close(); } return strHTML;
                }
            }
            catch (Exception exx)
            {
            }
            finally
            {
                if (webresponse != null)
                {
                    webresponse.Close();
                }
                if (request != null)
                    request.Abort();
            } return "";
        }
        public static string GetHtml_WinInet(string server, string url, string Header, string Method, string PostDate)
        {
            bool bRetCode = false;
            IntPtr hConn = IntPtr.Zero, hOpen = IntPtr.Zero, hOpenRequest = IntPtr.Zero; uint nBytesRead = 0; try
            {
                hConn = WinInet.InternetOpen("Microsoft Internet Explorer 6.0", WinInet.INTERNET_OPEN_TYPE_PRECONFIG, null, null, 0); 
                if (hConn != IntPtr.Zero)
                {
                    IntPtr hConnection = WinInet.InternetConnect(hConn, server, WinInet.INTERNET_DEFAULT_HTTP_PORT, null, "HTTP/1.1", WinInet.INTERNET_SERVICE_HTTP, 0, IntPtr.Zero); 
                    if (hConnection != IntPtr.Zero)
                    {
                        hOpenRequest = WinInet.HttpOpenRequest(hConnection, Method, url, "HTTP/1.1", null, 0, WinInet.INTERNET_FLAG_RELOAD, IntPtr.Zero); 
                        if (hOpenRequest != IntPtr.Zero)
                        {
                            WinInet.HttpSendRequest(hOpenRequest, Header, Header.Length, PostDate, PostDate.Length);
                            bRetCode = true; string strBuffer = "";
                            byte[] arBuffer = new byte[2048];
                            do
                            {
                                bRetCode = WinInet.InternetReadFile(hOpenRequest, arBuffer, 2048, ref nBytesRead);
                                if (bRetCode && nBytesRead > 0)
                                {
                                    strBuffer += Encoding.GetEncoding("GB2312").GetString(arBuffer, 0, (int)nBytesRead);
                                }
                                else if (!bRetCode)
                                {
                                }
                            } while (nBytesRead > 0);
                            return strBuffer;
                        }
                    }
                }
            }
            catch (Exception ex) 
            { 
                return "";
            }
            finally
            {
                if (hOpen != IntPtr.Zero) WinInet.InternetCloseHandle(hOpen);
                if (hConn != IntPtr.Zero) WinInet.InternetCloseHandle(hOpenRequest);
                if (hConn != IntPtr.Zero) WinInet.InternetCloseHandle(hConn);
            } return "";
        }
    }
}
Program.cs文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace WinNetAPIDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // 使用WinInet 
            int TickCount = System.Environment.TickCount;
            Console.WriteLine(MyHttp.GetHtml_WinInet("www.baidu.com", "/", "", "GET", ""));
            string timeText = (System.Environment.TickCount - TickCount).ToString();
            Console.WriteLine(timeText);
            // 使用HttpWebResponse
            TickCount = System.Environment.TickCount;
            MyHttp.GetHtml_HttpWebResponse("http://www.baidu.com", "GET", "");
            timeText = (System.Environment.TickCount - TickCount).ToString();
            Console.WriteLine(timeText);
            Console.ReadKey();
        }
    }    
}



 

你可能感兴趣的:(html,exception,String,Microsoft,null,internet)