C# 简单HTTP客户端 源代码
一、使用 Socket 类从 HTTP 服务器接收整个网页
using System; using System.Text; using System.Net; using System.Net.Sockets; public class GetSocket { private static Socket ConnectSocket(string server, int port) { Socket s = null; IPHostEntry hostEntry = null; // 获取服务器信息. hostEntry = Dns.GetHostEntry(server); // 循环地址列表以获取对应的协议类型的支持. // 很优雅 foreach (IPAddress address in hostEntry.AddressList) { IPEndPoint ipe = new IPEndPoint(address, port); Socket tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp); tempSocket.Connect(ipe); if (tempSocket.Connected) { s = tempSocket; break; } else { continue; } } return s; } // 向指定的服务器申请网页内容. private static string SocketSendReceive(string server, int port) { string request = "GET / HTTP/1.1\r\nHost: " + server + "\r\nConnection: Close\r\n\r\n"; Byte[] bytesSent = Encoding.UTF8.GetBytes(request); Byte[] bytesReceived = new Byte[256]; // 建立连接. Socket s = ConnectSocket(server, port); if (s == null) return ("连接失败"); // 向服务器发送请求. s.Send(bytesSent, bytesSent.Length, 0); // 接收服务器的主页内容. int bytes = 0; string page = server + "上的网页内容: \r\n"; // 以下块出于阻塞状态,直到接收完成. do { bytes = s.Receive(bytesReceived, bytesReceived.Length, 0); page = page + Encoding.UTF8.GetString(bytesReceived, 0, bytes); } while (bytes > 0); return page; } public static void Main(string[] args) { string host; int port = 80; if (args.Length == 0) // 如果没有输入参数,则用当前主机作为缺省参数. host = Dns.GetHostName(); else host = args[0]; string result = SocketSendReceive(host, port); Console.WriteLine(result); } }
二、使用 WebClient 类下载
using System; using System.ComponentModel; using System.Net; using System.Windows.Forms; namespace WebClientDownload { public partial class Form1 : Form { private bool isBusy; private WebClient client; public Form1() { InitializeComponent(); client = new WebClient(); // 订阅下载完成事件. client.DownloadFileCompleted += client_DownloadFileCompleted; // 订阅下载进度事件. client.DownloadProgressChanged += client_DownloadProgressChanged; } private void downloadButton_Click(object sender, EventArgs e) { // 如果正在下载中, 则取消下载. if (isBusy) { client.CancelAsync(); isBusy = false; downloadButton.Text = "下载"; } // 否则,下载 else { try { Uri uri = new Uri(urlTextBox.Text); downloadProgressBar.Value = 0; if (urlTextBox.Text.EndsWith("/")) client.DownloadFileAsync(uri, "localfile.htm"); else client.DownloadFileAsync(uri, urlTextBox.Text.Substring(urlTextBox.Text.LastIndexOf("/") + 1)); downloadButton.Text = "取消"; isBusy = true; } catch (UriFormatException ex) { MessageBox.Show(ex.Message); } } } // 显示下载是否完成的消息. private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { isBusy = false; downloadButton.Text = "下载"; if (e.Error == null) MessageBox.Show("下载完成"); else MessageBox.Show("下载未能完成: " + e.Error.Message); } // 刷新进度条 private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { downloadProgressBar.Value = e.ProgressPercentage; } } }
浙公网安备 33010602011771号