Changes

Internet Transfer Control in VB6

11,489 bytes added, 17:41, 24 November 2010
Reverted edits by [[Special:Contributions/Atekysepiko|Atekysepiko]] ([[User_talk:Atekysepiko|Talk]]); changed back to last version by [[User:Admin|Admin]]
The following lines were added (+) and removed (-):
This control is good for short pages only.  Microsoft's Internet Transfer control [http://support.microsoft.com/kb/q232194/ has a bug] whereby you will not always get the full contents of the page.  See the [[#WinInet_API_Alternative_.28work_around.29|WinInet section]] of this page for details on the work around. There is a fix out by Microsoft in the form of a service pack.  If you use the service pack fix then you won't need to concern yourself with the bug or work around.* [http://msdn2.microsoft.com/en-us/vstudio/aa718364.aspx Visual Studio Service Pack 6]== Inet Transfer Control / ITC ==The '''[http://support.microsoft.com/kb/q163653/ Internet Transfer ActiveX Control]''' component can be used to download files from the Internet.  ITC can be used to send and retrieve documents across the net.  ITC supports both synchronous and asynchronous transfers. In synchronous transfer, you can make the system wait until the transfer is complete, and in asynchronous transfer, the system can work as usual while the file is transferred in the background.Properties:AccessType property:*icUseDefault:*icDirect:*icNamedProxy:protocols:*icUnknown:*icDefault:*icFTP:*icGopher:*icHTTP:*icHTTPSicHTTP and icFTP*URL - The complete URL of what you want to communicate with. e.g. http://wiki.robotz.com/*RemoteHost - The name/IP address of the remote host you are connecting with.*RemotePort - The port to connect on. For HTTP connections, you want port 80. For FTP, port 21.*Document - The name of an individual document*UserName - Username to login with*Password - Password that goes with the username=== Inet Control States ===The Internet Transfer Control provides us with one event, StateChanged. And, when this event is raised, it provides only one parameters, State. We can use this parameter to detect what state the control is in, and then react accordingly.State constants:*icConnected (4) - Connected*icConnecting (3) - Connecting*icDisconnected (10) - Disconnected*icDisconnecting (9) - Disconnecting*icError (11) - An error has occurred*icHostResolved (2) - The remote address given has been accepted*icNone (0) - No current state*icReceivingResponse (7) - A response is current being received*icRequesting (5) - Data is currently being requested*icRequestSent (6) - A data request has been sent*icResolvingHost (1) - The remote address given is currently being checked*icResponseCompleted (12) - A response was successfully completed*icResponseReceived (8) - A response has been receivedin order by state number (same as above):<big><big> '  0 ........................ stateless '  1 .......... checking remote address '  2 .......... remote address accepted '  3 ....................... connecting '  4 ........................ connected '  5 .................. data requesting '  6 ..................... request sent '  7 ............... response receiving '  8 ................ response received '  9 .................... disconnecting ' 10 ..................... disconnected ' 11 ............................ error ' 12 .......................... success</big></big> Here is a State to Text Function you may find useful: Private Function StateText(n As Integer) As String  Select Case n    Case 0:    StateText = "stateless"    Case 1:    StateText = "checking remote address"    Case 2:    StateText = "remote address accepted"    Case 3:    StateText = "connecting"    Case 4:    StateText = "connected"    Case 5:    StateText = "data requesting"    Case 6:    StateText = "data sent"    Case 7:    StateText = "response receiving"    Case 8:    StateText = "response received"    Case 9:    StateText = "disconnecting"    Case 10:    StateText = "disconnected"    Case 11:    StateText = "error"    Case 12:    StateText = "success"    Case Else:    StateText = "that's weird"  End Select End FunctionicConnected provides you with a failsafe way of knowing that you are connected to a remote machine. As icDisconnected also provides you with a way of knowing when you are offline. Probably the most useful constant is icError. This tells us that an error has occurred.ErrorConstants:*icBadUrl*icCannotConnect*icConnectFailed*icConnectionAborted*icNoRemoteHost On Error Goto vbErrHand vbErrHand: Msgbox Err.DescriptionThere is no way to detect runtime errors.&nbsp;=== Using the OpenURL Method to Retrieve an HTML Page ===Example 1: VB6  <nowiki>Private Sub cmdGo_Click()</nowiki>  <nowiki>  inet.Protocol = icHTTP</nowiki>  <nowiki>  inet.URL = txtAddress.Text</nowiki>  <nowiki>  txtOut.Text = inet.OpenURL</nowiki>  <nowiki></nowiki>  <nowiki>End Sub</nowiki>  <nowiki></nowiki>  <nowiki>Private Sub Form_Load()</nowiki>  <nowiki>  txtAddress.Text = "http://wiki.robotz.com"</nowiki>  <nowiki>End Sub</nowiki>Example 2: Using byte array then converting Private Sub cmdGo_Click()  Dim bAr() As Byte, cnt As Integer  inet.Protocol = icHTTP  inet.URL = txtAddress.Text  bAr() = inet.OpenURL(, icByteArray)  txtOut.Text = StrConv(bAr, vbUnicode) End SubExample 3: VBA, Uses the internet transfer control with HTTP to create an HTML page.    <nowiki>Dim objInet as Inet</nowiki>  <nowiki></nowiki>  <nowiki>Private Sub Form_Load()</nowiki>  <nowiki>  ' Set a reference to the internet transfer control.</nowiki>  <nowiki>  Set objInet = Me!axInetTran.Object</nowiki>  <nowiki>End Sub</nowiki>  <nowiki></nowiki>  <nowiki>Private Sub cmdWriteFile_Click()</nowiki>  <nowiki>  Dim b() as Byte</nowiki>  <nowiki></nowiki>  <nowiki>  ' Set the internet transfer control protocol and URL.</nowiki>  <nowiki>  objInet.Protocol = icHTTP</nowiki>  <nowiki>  objInet.URL = "HTTP://www.microsoft.com"</nowiki>  <nowiki></nowiki>  <nowiki>  ' Retrieve the HTML data into a byte array.</nowiki>  <nowiki>  b() = objInet.OpenURL(objInet.URL,icByteArray)</nowiki>  <nowiki></nowiki>  <nowiki>  ' Create a local file from the retrieved data.</nowiki>  <nowiki>  Open "C:\Homepage.htm" For Binary Access Write As #1</nowiki>  <nowiki>  Put #1, , b()</nowiki>  <nowiki>  Close #1</nowiki>  <nowiki></nowiki>  <nowiki>  MsgBox "Done"</nowiki>  <nowiki>End Sub</nowiki>  <nowiki></nowiki>  <nowiki>Private Sub cmdGetHeader_Click()</nowiki>  <nowiki>  ' Set the internet transfer control protocol and URL.</nowiki>  <nowiki>  objInet.Protocol = icHTTP</nowiki>  <nowiki>  objInet.URL = "HTTP://www.microsoft.com"</nowiki>  <nowiki></nowiki>  <nowiki>  ' Open the HTML and display the header information.</nowiki>  <nowiki>  objInet.openURL objInet.URL, icByteArray</nowiki>  <nowiki>  MsgBox objInet.GetHeader</nowiki>  <nowiki>End Sub</nowiki>&nbsp;Example 3: Working example to Retrieve a File from an FTP Site  <nowiki>  strExe = "GET " & strSrc & " " & strDst</nowiki>  <nowiki>  With inet</nowiki>  <nowiki>    .Protocol = icFTP</nowiki>  <nowiki>    .UserName = "username"</nowiki>  <nowiki>    .Password = "password"</nowiki>  <nowiki>    .RemoteHost = "ftp.robotz.com"</nowiki>  <nowiki>    .Execute , strExe</nowiki>  <nowiki>  End With</nowiki>&nbsp;You can tell the program to continue while waiting for the connection to finish. 'Essential to avoid tying up the system Do Until inet.StillExecuting = False ' WAIT Downloading..  DoEvents Loop&nbsp;== WinInet API Alternative (work around) ==When you use the OpenUrl method of Microsoft Internet Transfer Control (ITC) to download files from Web servers, the resulting files may not be complete if the server uses "chunked" transfer-encoding to send the HTTP response data. ITC allocates a buffer of 64K bytes and calls InternetReadFile in a loop. Whenever the buffer containing the read data is not full after the API returns, ITC will exit the loop. However, InternetReadFile can return when less than the total number of bytes requested were read into the buffer, which causes the problem. This is the case if the transfer-encoding is chunked.Ref: http://support.microsoft.com/kb/q232194/Note:  The bug was corrected in a service pack for Visual Studio 6.0.  You may use the service pack rather than this work around below.A way to work around this problem is to call the WinInet APIs directly in Visual Basic, as described in the following two steps:=== Work Around Step 1 ===  <nowiki>Option Explicit</nowiki>  <nowiki></nowiki>  <nowiki>Public Const INTERNET_OPEN_TYPE_PRECONFIG = 0</nowiki>  <nowiki>Public Const INTERNET_OPEN_TYPE_DIRECT = 1</nowiki>  <nowiki>Public Const INTERNET_OPEN_TYPE_PROXY = 3</nowiki>  <nowiki></nowiki>  <nowiki>Public Const scUserAgent = "VB OpenUrl"</nowiki>  <nowiki>Public Const INTERNET_FLAG_RELOAD = &H80000000</nowiki>  <nowiki></nowiki>  <nowiki>Public Declare Function InternetOpen Lib "wininet.dll" Alias "InternetOpenA" _</nowiki>  <nowiki>(ByVal sAgent As String, ByVal lAccessType As Long, ByVal sProxyName As String, _</nowiki>  <nowiki>ByVal sProxyBypass As String, ByVal lFlags As Long) As Long</nowiki>  <nowiki></nowiki>  <nowiki>Public Declare Function InternetOpenUrl Lib "wininet.dll" Alias "InternetOpenUrlA" _</nowiki>  <nowiki>(ByVal hOpen As Long, ByVal sUrl As String, ByVal sHeaders As String, _</nowiki>  <nowiki>ByVal lLength As Long, ByVal lFlags As Long, ByVal lContext As Long) As Long</nowiki>  <nowiki></nowiki>  <nowiki>Public Declare Function InternetReadFile Lib "wininet.dll" _</nowiki>  <nowiki>(ByVal hFile As Long, ByVal sBuffer As String, ByVal lNumBytesToRead As Long, _</nowiki>  <nowiki>lNumberOfBytesRead As Long) As Integer</nowiki>  <nowiki></nowiki>  <nowiki>Public Declare Function InternetCloseHandle Lib "wininet.dll" _</nowiki>  <nowiki>(ByVal hInet As Long) As Integer</nowiki>=== Work Around Step 2 ===  <nowiki>Private Sub Command1_Click()</nowiki>  <nowiki>    Dim hOpen              As Long</nowiki>  <nowiki>    Dim hOpenUrl            As Long</nowiki>  <nowiki>    Dim sUrl                As String</nowiki>  <nowiki>    Dim bDoLoop            As Boolean</nowiki>  <nowiki>    Dim bRet                As Boolean</nowiki>  <nowiki>    Dim sReadBuffer        As String * 2048</nowiki>  <nowiki>    Dim lNumberOfBytesRead  As Long</nowiki>  <nowiki>    Dim sBuffer            As String</nowiki>  <nowiki></nowiki>  <nowiki>    sUrl = "http://www.microsoft.com"</nowiki>  <nowiki>    </nowiki>  <nowiki>    hOpen = InternetOpen(scUserAgent, INTERNET_OPEN_TYPE_PRECONFIG, vbNullString, vbNullString, 0)    </nowiki>  <nowiki>    hOpenUrl = InternetOpenUrl(hOpen, sUrl, vbNullString, 0, INTERNET_FLAG_RELOAD, 0)</nowiki>  <nowiki></nowiki>  <nowiki>    bDoLoop = True</nowiki>  <nowiki>    While bDoLoop        </nowiki>  <nowiki>        sReadBuffer = vbNullString</nowiki>  <nowiki>        bRet = InternetReadFile(hOpenUrl, sReadBuffer, Len(sReadBuffer), lNumberOfBytesRead)</nowiki>  <nowiki>        sBuffer = sBuffer & Left$(sReadBuffer, lNumberOfBytesRead)</nowiki>  <nowiki>        If Not CBool(lNumberOfBytesRead) Then bDoLoop = False</nowiki>  <nowiki>    Wend</nowiki>  <nowiki>    </nowiki>  <nowiki>    Open "C:\Temp\log.txt" For Binary Access Write As #1</nowiki>  <nowiki>    Put #1, , sBuffer</nowiki>  <nowiki>    Close #1</nowiki>  <nowiki>    </nowiki>  <nowiki>    If hOpenUrl <> 0 Then InternetCloseHandle (hOpenUrl)</nowiki>  <nowiki>    If hOpen <> 0 Then InternetCloseHandle (hOpen)</nowiki>  <nowiki>End Sub </nowiki>
Bureaucrat, administrator
16,192
edits