close
手工打造 HTTP Client

未測試成功

using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
// HttpClient http://ccckmit.wikidot.com/ teach teach.htm
public class HttpClient
{
    public static void Main(string[] args)
    {
        // download("tw.msn.com", "/", "msn.htm");
        download("127.0.0.1", "/index.htm", "localindex.htm");
    }
    public static void download(String site, String path, String toFileName)
    {
/*        IPHostEntry hostEntry = Dns.GetHostEntry(site);
        foreach (IPAddress addr in hostEntry.AddressList)
        {
            Console.WriteLine("address = "+addr);
        }
        IPAddress ipAddress = hostEntry.AddressList[0];
//        IPEndPoint ipep = new IPEndPoint(ipAddress, 80);
 */
        IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(site), 80);
        //        IPEndPoint ipep = new IPEndPoint(ipAddress, 80);
        Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        server.Connect(ipep);
        String head = "GET " + path + " HTTP/1.0\n\n";
        byte[] headbuf = Encoding.UTF8.GetBytes(head);
        server.Send(headbuf);
        NetworkStream stream = new NetworkStream(server);
        StreamReader reader = new StreamReader(stream);
        int contentLength = 0;
        while (true)
        {
            String line = reader.ReadLine();
            if (line.StartsWith("Content-Length:"))
                contentLength = int.Parse(line.Substring("Content-Length:".Length));
            Console.WriteLine(line);
            if (line.Length == 0) break;
        }
        byte[] buf = new byte[contentLength];
        reader.ReadBlock(buf, 0, contentLength);
        FileStream outFile = new FileStream(toFileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
        outFile.Write(buf, 0, buf.Length);
        outFile.Close();
        server.Shutdown(SocketShutdown.Both);
        server.Close();
    }
}
	

陳鍾誠 (2013年03月25日),(網頁標題) Httpclient,(網站標題) 免費電子書:C# 程式設計,2013年03月25日,取自 http://cs0.wikidot.com/httpclient ,網頁修改第 0 版。

arrow
arrow

    Johnson峰 發表在 痞客邦 留言(0) 人氣()