All vb inet controls

Source: Internet
Author: User
Tags call shell ftp commands ftp connection informix ftp browser ftp protocol ftp transfer

The Internet transfer control implements two widely used Internet protocols: Hypertext Transfer Protocol (HTTP) and file transfer protocol (FTP ). Using the Internet transfer control, you can use the Openurl or execute method to connect to any site that uses the two Protocols and retrieve files.

Possible Use
Add an FTP browser to the application.

Create an application that automatically downloads files from the public FTP site.

Analyze the image reference in the World Wide Web site and download only the image.

Provides custom display of dynamic data obtained from web pages.
Basic operations
The functions of the Internet transfer control depend on the Protocol to be used. Because the two supported protocols work differently, the operations that can be performed depend on the protocols in use. For example, the getheader method can only be used for HTTP (HTML document) protocols.

However, some processes are common to the two Protocols. The most basic, if you want to use any protocol, you must:

Set the accesstype attribute to a valid proxy server.

Use a valid URL to call the Openurl method.

Use valid URLs and commands supported by the Protocol to call the execute method.

Use the getchunk method to obtain data from the buffer.
Set the accesstype attribute: Use the Proxy Server
To establish any form of connection with the internet, you must determine how the computer connects to the Internet. If it is on the Intranet, a proxy server may be required to connect to the Internet.

In short, the proxy server is the medium between the computer and the Internet. All computers on the intranet that need to be connected to the Internet must use the proxy server. The proxy can use the firewall between the intranet and the Internet to block illegal end users and external requests, thus protecting the intranet from being damaged.

To find the proxy settings on your computer, follow these steps:

Note that the following steps can only be performed on Windows 95 and Windows NT (R) 4.0 systems.

In the computer's "Taskbar", click "start ".

In settings, click Control Panel ".

Double-click "Internet.

In the Internet Properties dialog box, click Connect ".

In "Proxy Server", confirm that the "connect through proxy server" check box is selected.

If selected, click "set ". In this dialog box, you can find the name of the proxy server that can be used for multiple protocols. If no proxy server is defined, contact the system administrator to obtain the available proxy server.
To use proxy servers not listed in the dialog box, set the AccessType attribute to icNamedProxy (2 ). Set the Proxy property to the name of the Proxy server, as shown in the following code:

Inet1.Proxy = "myProxyName"
Inet1.AccessType = icNamedProxy

On the other hand, if you want to use the default Proxy Server (determined by the computer's Registry), you can ignore the Proxy attribute, instead of setting AccessType to icUseDefault (0 ).

The values of AccessType are listed in the following table:

Constant Value description
IcUseDefault 0 (default) is used as the default value. Controls use the default settings in the Registry to access the Internet.
IcDirect 1 directly connects to the Internet. This control can be directly connected to the Internet.
The proxy server named icNamedProxy 2. Indicates the Proxy server that the control uses the Proxy property to determine.

Call OpenURL
After setting the AccessType attribute, the most basic operation is to call the OpenURL method with a valid URL. When the OpenURL method is used, the result of the operation depends on the target URL. For example, the following URL will return the HTML document found in www.microsoft.com:

The TextBox Control named "Text1" is saved
'Result of this method. Internet transmission
'The Control name is "Inet1 ".
Text1.Text = Inet1.OpenURL ("http://www.microsoft.com ")

As a result, the TextBox Control saves the HTML source code, which should look similar to the display:

In this case, the default operation returns the HTML document located in the URL. However, if the URL is changed to a text file, the actual file is obtained. For example, the following code:

Text1.Text = Inet1 ._
OpenURL ("ftp://ftp.microsoft.com/disclaimer.txt ")

The actual text of the file is as follows:

It indicates that you do not need to set the Protocol attribute when using the OpenURL or Execute method. The Internet Transfer control is automatically set based on the protocol specified in the URL protocol section.

Finally, you can call the Openurl method with a URL containing additional data. For example, many web sites provide the ability to search databases. To search for a database, you need to include search criteria in the sent URL. For example, the following code uses the condition "find?maui=" to call the search.exe" search engine.

Dim strurl as string
Strurl = _
"Http://www.howzit.com/cgi-bin/search.e Xe? Find = Maui
Text1.text = inet1.openurl (strurl)

If the search engine finds the Matching content, it will combine an HTML document and carry the appropriate information to return.

Use Openurl to save the file
If you need to save the data obtained through the Openurl method to a file, you can use the open, put, and close statements, as shown in the following code. In this example, the obtained binary file is first transmitted to the byte array, and then the data is saved to the disk:

Dim strurl as string
Dim bdata () as byte data variable
Dim intfile as integer 'available file variables
Strurl = _
"Ftp://ftp.microsoft.com/Softlib/Softlib.e XE"
Intfile = freefile () 'sets intfile to an unused File
'The result of the Openurl method is first passed into the byte array,
'Then save the byte array to the disk.
Bdata () = inet1.openurl (strurl, icbytearray)
Open "C: \ temp \ softlib. e XE" for binary access write _
As # intfile
Put # intfile, bdata ()
Close # intfile

A similar process can be used to write text files to the disk. The difference is that the byte array is no longer needed, and the data can be saved directly to the file:

Dim strurl as string 'url string
Dim intfile as integer 'available file variables
Intfile = freefile ()
Strurl = "http://www.microsoft.com"
Open "C: \ temp \ mssource.txt" for output _
As # intfile
Write # intfile, inet1.openurl (strurl)
Close # intfile

Synchronous and asynchronous transmission
The Openurl method transmits data synchronously. Here, synchronization means that other processes cannot be executed before the transmission operation is completed. In this way, data transmission must be completed before other code is executed.

The execute method transmits data asynchronously. When the execute method is called, the transfer operation is irrelevant to other processes. In this way, after the execute method is called, other code can be executed simultaneously while receiving data in the background.

What does this mean for users of the Internet Transfer control? Simply put, the OpenURL method can be used to directly obtain data streams that can be stored on the disk (as described above), or directly read data in the TextBox Control (if the data is in text format ). On the other hand, if you use the Execute method to obtain data, you must use the StateChanged event to monitor the connection status of the control. When the desired status is reached, call the GetChunk method to obtain data from the control's buffer zone. This operation is discussed in more detail below.

Execute method in FPT Protocol
The Execute method has four parameters: url, operation, data, and requestHeaders. FTP only uses the operation parameter and url parameter, and the latter is optional. For example, to get a file from a remote computer, use the following code:

Inet1.Execute "FTP: // ftp.microsoft.com ",_
"GET disclaimer.txt C: \ Temp \ Disclaimer.txt"

If you are using FTP to obtain files from an anonymous FTP server, you should be familiar with the specific commands roaming in the server directory tree, And the commands getting the files to the local hard disk. For example, to change the directory using the FPT protocol, use the "CD" command with the directory path you want to change.

For most common operations, such as transferring files to the server and obtaining files from the server, the Internet transmission control uses the same or similar commands (as FTP) in the Execute method. For example, the following code uses the "CD" command as a parameter of the Execute method to change the path:

The 'txturl text box contains the path to be opened.
The 'txtremotepath textbox contains the path to be changed.
Inet1.Execute txtURL. Text, "CD" & txtRemotePath. Text

Note that the data and requestHeaders parameters are not used when using the FTP command in the Execute method. All operations and their parameters are transmitted as strings in the operation parameter. parameters are separated by spaces. In the following description, do not mix "file1" and "file2" with the data and requestHeaders parameters.

The FTP operation syntax is:

OperationName file1 file2

For example, to obtain a file, the following code contains the operation name ("get") and the two file names required for this operation:

'Get to the file named disclaimer.txt, and copy it
'C: \ Temp \ Disclaimer.txt.
Inet1.Execute ,_
"GET Disclaimer.txt C: \ Temp \ Disclaimer.txt"

The following table lists the FTP commands supported by the control:

Operation Description Example
CD file1 changes the directory. Changed to the directory specified by file1. Execute, "CD docs \ mydocs"

CDUP changes to the parent directory. Function is the same as "CD. Execute, "CDUP"

DELETE file1: DELETE a file specified by file1. Execute, "DELETE discard.txt"

DIR [file1] is located in the directory specified by file1. If the file1 directory is not specified, find the current working directory. Use the GetChunk method to return data. Execute, "DIR/mydocs"

GET file1 file2 gets the remote file specified by file1 and creates a new local file specified by file2. Execute ,_
"Get getme.txt c: \ gotme.txt"

Mkdir file1 creates a directory specified by file1. Successful execution depends on the user's permissions on the remote host. Execute, "mkdir/mydir"

Put file1 file2 copies the local file specified by file1 to the remote host file specified by file2. Execute ,_
"Put c: \ putme.txt/putme.txt"

PWD prints the working directory. Returns the name of the current directory. Use the getchunk method to return data. Execute, "PWD"

Quit ends the current connection. Execute, "quit"

Recv file1 file2 is the same as get. Execute ,_
"Recv getme.txt c: \ gotme.txt"

Rename file1 file2 file. Successful execution depends on the user's permissions on the remote host. Execute,
"RENAME old.txt new.txt"

Rmdir file1: Delete the directory. Successful execution depends on the user's permissions on the remote host. Execute, "rmdir olddir"

Send file1 to copy the file to the FTP site. (Same as put) execute ,_
"Send C: \ putme.txt/putme.txt"

Size file1 returns the size of the file specified by file1. Execute "size/largefile.txt"

If the proxy server is a CERN proxy server, direct FTP connections (using the Execute method) are not allowed ). In this case, to obtain the file, you need to use the OpenURL method with the Open, Put, and Close statements, as mentioned in the previous section "Save to file using the OpenURL method. You can also use the OpenURL method to obtain the directory list, which uses the target directory as the URL and call this method.

Execute on HTTP
HTTP allows the client to request data from the server with GET, HEAD, POST, and PUT commands. The following table lists these operations:

Operation Description Example
GET gets the file named in the url. Execute "http://www.microsoft.com "&_
"/Default.htm", "GET"

HEAD only obtains the file header of the file named in the URL attribute. Execute, "HEAD"

POST provides additional data to support requests to remote hosts. Execute, "POST", strFormData

PUT replaces the data in the specified URL. Execute, "PUT", "replace.htm"

Common Gateway Interface and Execute Method
Many World Wide Web sites provide the ability to search databases. It uses the HTTP protocol to send queries using the Common Gateway Interface (CGI.

We will not discuss CGI here. However, if you are familiar with CGI, you can use the Execute method to construct an application to simulate the behavior of the World Wide Web site. For example, the following code provides a typical CGI query string:

Http://www.yippee.com/cgi-bin/find.e xe? Find = Hangzhou

As shown in the following figure, the same query can be sent using the Execute method:

Dim strURL As String, strFormData As String
StrURL = "// www.yippee.com/cgi-bin/find.e xe"
StrFormData = "find = Hangzhou"
Inet1.E xecute strURL, "POST", strFormData

If you want to get the result returned from the server (as shown in the preceding example), you must use the GetChunk method to obtain the HTML document as the result.

Use the GetChunk method in the State event
An asynchronous connection is established when data is downloaded from a remote computer. For example, if you use the "get" Operation in the Execute method, the server will obtain the requested file. After obtaining the entire file, the State parameter returns icResponseCompleted (12 ). At this time, you can use the GetChunk method to obtain data from the buffer. The following example shows the situation:

Private Sub inetaskstatechanged (ByVal State As Integer)
Dim vtData As Variant data variable.
Select Case State
'... No other information is provided.
Case icResponseCompleted '12
'Open the file for writing.
Open txtOperation For Binary Access _
Write As # intFile

'Get the first bulk. Note: Specify the Byte array
'(Icbytearray) to obtain binary files.
Vtdata = inet1.getchunk (1024, icstring)

Do While lenb (vtdata)> 0
Put # intfile, vtdata
.
Vtdata = inet1.getchunk (1024, icstring)
Loop
Put # intfile, vtdata
Close # intfile
End select
End sub

Log on to the FTP server
There are two types of FTP servers: public and private. Public servers, as the name suggests, are open to everyone. In addition to the real users of the private server, other users cannot log on to the server. In both cases, the FTP protocol requires the user name and password. These two parameters are used to verify the user and allow (or disable) further operations.

To log on to the public server, the usual practice is "anonymous" login (username = "anonymous"), and then send the user's email name as the password. However, the process of using the Internet transmission control can be further simplified. By default, if the username and password attribute values are not provided, the control sends "anonymous" as username, and the user's email name as password.

To log on to the private server, set the username, password, and URL attributes as appropriate and call the execute method, as shown in the following example:

With inet1
. Url = "ftp://ftp.someFTPSite.com"
. Username = "John Smith"
. Password = "Maui & 9 $6"
. Execute, "dir" 'to return to this directory.
. Execute, "close" 'Close the connection.
End

After the execute method is called, the FTP connection is still open. In this case, you can continue to use the execute method to complete other ftp operations, such as CD and get. If the session has been completed, execute the close operation to close the connection. You can also change the URL attribute and call the Openurl or execute method to automatically close the connection. This operation will close the current FTP connection and open a new URL.

For FTP, you can use the execute method to execute the FTP command size to obtain the file size. Then, the size of the returned file can be obtained in the statechanged event.
Private sub commandementclick ()
Inet1.execute "ftp: // 127.0.0.1", "size 1.gif"
End sub

Private sub inetaskstatechanged (byval state as integer)
When 'State = 12, use the getchunk method to retrieve the server response.

Dim vtdata as variant 'data variable.
Select case state
'... No other cases are listed.
Case icerror '11
'Responsecode and responseinfo are returned when an error occurs.
VtData = Inet1.ResponseCode &":"&_
Inet1.ResponseInfo
Case icResponseCompleted '12

Dim strData As String
Dim bDone As Boolean: bDone = False

'Get the first block.
VtData = Inet1.GetChunk (1024, icString)
DoEvents

Do While Not bDone
StrData = strData & vtData
'Get the next block.
VtData = Inet1.GetChunk (1024, icString)
DoEvents

If Len (vtData) = 0 Then
BDone = True
End If
Loop
MsgBox strData
End Select

End Sub

For HTTP download, you can use GetHeader (Content-length) to obtain the file size. But not all HTTP Downloads can get the file length, especially when downloading files through the proxy server. For example:
Private Sub Form_Load ()
Inet1.Execute "http://askpro.yeah.net /"
End Sub

Private sub inetaskstatechanged (byval state as integer)
If State = icresponsereceived then
Msgbox "file size is" & inet1.getheader ("Content-Length ")
End if
End sub

========================================================== ======

Implement file upload in VB
As an integrated development environment integrating application development, testing, and error checking, Visual Basic is increasingly favored by programmers. During the development of a database maintenance system, I chose VB5.0 as the development platform, Unix as the server operating system, and Informix as the server database.
Problem
During the development of the maintenance system, the function filetoclob ("FILENAME", "server") is required when the field type clob of INFORMIX database is filled in data "), the file path and name must be specified for "FILENAME. However, this file is executed on the client during maintenance, which requires immediate transfer of the file to the server.
Solution
1. FTP Transfer Tool
First, we need to use the FTP transmission tool and the shell command in VB5.0 to call the DOS batch file for transmission.
Shell call format:
Shell (pathname [, windowstyle])
Example: Shell ("C: \ WINDOWS \ upload. Bat ")
Content of the batch file upload. BAT:
C: \ windows \ ftphostname
Username
Password
Sendc: \ zrh \ upload.txtupload.txt
Bye
This command meets the transmission requirements of the file "upload.txt. After use, call the command to delete the file.
Example: Shell ("c: \ windows \ del_up.bat ")
Batch File del_up.bat content:
C: \ windows \ ftphostname
Username
Password
Deleupload.txt
Bye
In this way, the file "upload.txt" is deleted.
However, another problem occurs. Because the running mechanism of Shell functions is synchronous with other programs, that is to say, the statements following Shell functions have been executed before the subprograms that call Shell functions have been completed. When a large volume of data is added, the file of a record is not uploaded, And the next Insert statement is called. In this way, an error occurs during ODBC calling.
2. INET Control
The InternetTransfer control provides the two most commonly used protocols on the Internet: HTTP and FTP. You can use the HTTP protocol to connect to the WWW server to download files, and use the FTP protocol to log on to the FTP server. Common FTP commands, such as CD and GET, can be implemented through the Execute method.
The following is an example of setting INET control attributes.
Inet1.URL = ftp: // username: password @ hostname/document
Inet1.Protocol = 2-icFTP
Inet1.RemoteHost = hostname
Inet1.RemotePort = 21
Inet1.Username = username
Inet1.Password = password
Execute file transfer:
Inet1.Execute "ftp: // username: password @ hostname ",_
"PUT" & local_filename & "UPLOAD1.TXT"
Right1 = Inet1.StillExecuting
DoWhileright1
Right1 = Inet1.StillExecuting
DoEvents
Loop
This allows you to upload files.
* Advantages of the SINET Control
The difference between the INET control and the Shell () function is that the INET Control calls the statement
Right1 = Inet1.StillExecuting
DoWhileright1
Right1 = Inet1.StillExecuting
DoEvents
Loop to control the order of statement execution. Before the file transfer is complete, the program will not execute other statements, and naturally there will be no problems in calling Shell functions. The right1 variable is used to test the execution status of inet1. If file transfer is still in progress, the DoEvents method is called to give the system free time for file transfer, in this way, the file upload function is successfully executed. The file will be deleted after use.
Inet1.execute "ftp: // Informix: Informix @ rd ",_
"Deleteupload1.txt"
Right1 = inet1.stillexecuting
Dowhileright1
Right1 = inet1.stillexecuting
Doevents
Loop
Delete the uploaded files to avoid occupying disk space on the server.
* S uses the statechanged event prompt information
The server also activates the inetaskstatechanged event while executing inet1.exe cute. The process can perform the action based on the captured status.
Object_statechanged (byvalstateasinteger)
State: integer
The following describes the status.
Icnone
0. Status ichostresolvinghost not reported
1. The control is searching for the IP address ichostresolved of the specified host.
2. The control has successfully found the IP address icconnecting of the specified host.
3. The control is connecting to the specified host. icconnected
4. The control has successfully connected icrequesting to the specified host.
5. The control is sending an icrequestsent request to the host.
6. The control has successfully sent a request to the host icreceivingresponse.
7. The control is receiving feedback from the host. icresponsereceived
8. The control has successfully received feedback from the host icdisconnecting.
9. The control is disconnecting from the host.
10. The control is disconnected from the host.
11. An icresponsecompleted error occurred while communicating with the host.
12. The request is complete and the data has been received
The following is an example.
Privatesubinet1_statechanged (byvalstateasinteger)
'Retrieveserverresponseusingthegetchunk
'Methodwhenstate = 12. thisexampleassumesthe
'Dataistext.
Selectcasestate
'... Othercasesnotshown.
Caseicresponsereceived '12
Dimvtdataasvariant 'datavariable.
Dimstrdataasstring: strdata = ""
Dimbdoneasboolean: bdone = false
'Getfirstchunk.
Vtdata = inet1.getchunk (1024, icstring)
Dowhilenotbdone
Strdata = Data & vtdata
'Getnextchunk.
Vtdata = inet1.getchunk (1024, icstring)
IfLen (vtData) = 0 Then
BDone = True
EndIf
Loop
TxtData. Text = strData
EndSelect
EndSub

========================================================== =
Method 2: Set the information:
Inet1.Protocol = icFTP
Inet1.RemoteHost = servername' server address
Inet1.RemotePort = 21 'ftp Port
Inet1.UserName = uname' User Name
Inet1.Password = uPWS 'Password

Download file:
Inet1.Execute "", "GET 1.txt d: \ 1.txt"
Ri = Inet1.StillExecuting
Do While ri
Ri = Inet1.StillExecuting
DoEvents
Loop
Upload files:
Inet1.Execute "", "PUT d: \ 1.txt 1.txt"
Ri = Inet1.StillExecuting
Do While ri
Ri = Inet1.StillExecuting
Doevents
Loop

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.