日期:2014-01-31  浏览次数:20431 次


HTTP协议是文本格式通讯,下载文件是二进制数据,怎样处理好两种格式,而不受VB独断专行的Unicode转换影响,本代码提供了一个示例。

Option Explicit
Private strURL As String
Private mstrFileName As String, mlngFileNum As Long
Private mlngFileLen As Long, mlngCurByte As Long
Private mblnOnlyLen As Boolean, mblnPutStart As Boolean
Private Sub Form_Load()
    strURL = Text1.Text '准备下载的文件URL
    mstrFileName = Text2.Text   '下载文件在本存放的位置与文件名
    Label1.Caption = "文件总字节:0"
    Label2.Caption = "已下载字节:0"
    Command1.Caption = "开始下载"
    Command2.Caption = "取得长度"
End Sub
Private Sub Command1_Click()
    mblnOnlyLen = False
    DownFile
End Sub
Private Sub Command2_Click()
    mblnOnlyLen = True
    Label1.Caption = "文件总字节:0"
    DownFile
End Sub
Private Sub DownFile()
    mblnPutStart = False
    Label2.Caption = "已下载字节:0"
    Command1.Enabled = False
    Command2.Enabled = False
    With Winsock1
        If .State <> sckClosed Then .Close
        .Protocol = sckTCPProtocol
        .RemoteHost = "article.tianyaclub.com"
        .RemotePort = 80
        .Connect
    End With
End Sub

Private Sub Winsock1_Connect()
    Dim s As String
    s = "GET " + strURL + " HTTP/1.0" + vbCrLf
    s = s + "Accept: */*" + vbCrLf
    s = s & "Pragma: no-cache" & vbCrLf
    s = s & "Cache-Control: no-cache" & vbCrLf
    s = s & "Connection: close" & vbCrLf & vbCrLf
    s = s + vbCrLf
    Winsock1.SendData s
End Sub
Private Sub CloseAll()
    If Winsock1.State <> sckClosed Then Winsock1.Close
    Close #mlngFileNum
    Command1.Enabled = True
    Command2.Enabled = True
End Sub
Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
    Dim RevData() As Byte
    Dim a() As Byte, b() As String, c() As String
    Dim s As String, i As Long, k As Long
    On Error GoTo fail
    If mblnPutStart = False Then
        Winsock1.PeekData RevData, vbArray Or vbByte
        k = InStrB(1, RevData, ChrB(13) & ChrB(10) & ChrB(13) & ChrB(10))
        If k > 0 Then
            Winsock1.GetData RevData, vbArray Or vbByte
            a = LeftB(RevData, k - 1)
            RevData = MidB(RevData, k + 4)
            s = StrConv(a, vbUnicode)
            b = Split(s, vbCrLf)
            If InStr(1, b(0), "200 OK", vbTextCompare) = 0 Then GoTo fail
            For i = 1 To UBound(b)
                c = Split(b(i), ": ")