Httpclient

基礎篇

C# 簡介

開發環境

變數與運算

流程控制

陣列

函數

物件

例外處理

函式庫篇

檔案處理

資料結構

正規表達式

Thread

應用篇

視窗程式

媒體影音

網路程式

遊戲程式

手機程式

資料庫

雲端運算

特殊功能

委派

擴展方法

序列化

LinQ

WPF

網路資源

教學影片

投影片

教學文章

軟體下載

考題解答

101習題

未測試成功

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();
    }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License