TIEHTTP - Delphi HTTP/HTTPS GET/POST component
 
[login] [about] [menu]

 

 
For support please use the Message Board

TIEHTTP - Delphi HTTP/HTTPS GET/POST Component


TIEHTTP - The Internet Explorer HTTP/HTTPS GET/POST component (WinInet)
 

 Author:  Kyriacos Michael
 Latest Update:  03/May/2008
 Version:  1.5.0.66
 Supported Platforms:  Delphi 6, Delphi 7, Delphi 2005, Delphi 2006, Delphi 2007
 License:  Freeware (*)
 Source Code:  included

(*) Free for either commercial or non-commercial use. No need to add any kind of references for the component.

Component home: http://www.myfxboard.com/tiehttp/
Download: http://www.myfxboard.com/tiehttp/TIE_http_https_build_066.rar

Description:

This component uses the IE's HTTP / HTTPS mechanism (WinInet) to connect to a web server and perform GET or POST operations, (either multipart or urlencoded).

It supports content decompression, invalid or expired https certificates, and uses the existing proxy settings for the current connection so the only thing you will need is to set the URL and call the execute method.

It also supports unicode, and can automatically convert from UTF-8, UTF-16 and ANSI encodings

Installation Instructions:

Prepare

Unzip the files in a directory and make sure this directory is in your library paths
( Delphi -> Tools / Options / Library-Win32 / Library path ).
( e.g. c:\components\tiehttp\ )

The component includes an extra gunzip directory, so make sure this directory is also in your library paths ( e.g. c:\components\tiehttp\gunzip\source\ )
If you do not want gzip decompression you can disable it in tiehttp.inc by changing
{$DEFINE TIEHTTP_GUNZIP} to {.$DEFINE TIEHTTP_GUNZIP} (more details in settings section below)

Install

Open TIE_http_https.dpk and click install. You will find the new TIEHTTP component under the "Internet" tab of the Delphi component palette.

 

Settings - tiehttp.inc

{$DEFINE TIEHTTP_GUNZIP} //default=ON
Enable this to allow aspx gzip decompression.

Tthe component allows decompression of
Z - ZLIB -- for content compressed with php gzcompress
G - GZIP -- for content compressed with aspx GZipStream

The gunzip units are included in the distribution of TIEHTTP
When you enable this option you will need to add the path to gunzip
(e.g. c:\components\tiehttp\gunzip\source\)
in your library paths ( Delphi -> Tools / Options / Library-Win32 / Library path )

{.$DEFINE TIE_USE_TNT} //default=OFF
Enable this to use TTNTStringList instead of TWideStringList
In Delphi 7, you will need to enable this to handle unicode http responses
to enable this you will need to have the full tnt components suite installed
if this is disabled,
1. a tntlite unit with only some necesarry methods will be used instead, and
2. a standard TAnsiStringList will be used instead of a TWideStringList

Properties:

URL: A full URL to be used in a GET or POST operation. You may use a complete URL including the protocol, port, server name, script name and parameters, all in one line, exactly as you can find it in the address bar or IE.

If you would like to connect to a secure server just prefix the server name with "https://". Otherwise the default "http://" will be automatically used.

Request Method: Either a GET or POST method.

Request_Headers: (new) A TStringList that accepts extra headers to be sent to the server.

e.g. to change the Referer header:
request_headers.Add('Referer: http://xxx');

Multipart POST: Whether to use a "multipart" or "urlencoded" content type. By setting multipartPOST to true, the "Request Method" is automatically set to POST.

GetStr: A variables' list in the form of "var1=1&var2=2&var3=3" that will be forced to be passed in the URL even if the Request Method is set to true;

PostStr: A variables' list in the same form as with GetStr that will be posted to the server. These variables will be automatically converted to multipart it the MultipartPOST option is enabled.

result_sl: A TStringList variable that holds the text-only results (such as the html text) retrieved from the server after an Execute method has been performed. Another alias for this is simply "sl".

result_ms: A TMemoryStream holding the web server reply in binary format.

username/password: http/https authentication information

contentsize: The size of the content to be received. The availability of this information depends on the location you access. If it is an asp or php script the web server may not be able to determine the size of the response.

total_bytes_read: Total byres read. Can be used in the OnPacketRead event with the contentsize property to display the download progress of a lengthy response.

timeout: Specifies a timeout interval in seconds. If there is no download activity during that interval the component will stop processing the request. The counter gets reset whenever there is download activity.

TimerIntervalSeconds: Specifies the number of seconds that will cause the OnTimer event to fire.

BlockingMode: Set this to false to be able to cancel requests.

If blocking mode is set to true (Default) you will not be able to interact with your application, until the component finishes downloading the entire content from the server. Non-blocking mode allows you have a "cancel" button that will call iehttp1.StopRequest in order to force the component to stop the communication.

proxy_username / proxy_password: Login information for basic proxy authentication 

Methods:

Execute: This will use the current URL to perform a GET or POST operation.

ExecuteURL: The same as above, except you can set the URL directly here.

AddMultipartVar: Adds a variable to be posted in multipart format. You will need to set the MultipartPOST property to true before adding variables.

AddMultipartFile(variable: string, filename: string):
Loads the specified file from the disk, performs a base64 encoding, and sets the necessary headers to be transferred.

AddMultipartFormFile(variable: string, filename: string):
Loads the specified file from the disk, and prepares file for binary transfer.
The file is transfered using standard form-upload. (see examples below on how to handle file using PHP and ASPX)

AddMultipartStream(variable: string, ms: TMemoryStream):
Encodes the stream's contents based on the base64 algorithm and prepares the stream for upload.

StopRequest: Forces the component to stop the current request. You must have "blockingMode" set to false, in order to be able to use this method. 

Events:

OnPacketRead: Fires when 4k bytes of data have been read, and can be used to update a ProgressBar conrol to show the status of the download.

OnTimer: Fires every time the period specified in TimerIntervalSeconds, elapses.

 

Examples:

1. Simple GET

The following example will use the GET method (default if none specified) to fetch the contents of the given url

iehttp1.ExecuteURL('http://www.myserver.com/script1.php?var1=1');
showmessage(iehttp1.sl.text); //show the results

 

2. Simple POST

The following example will use the POST method  to post the var1 variable to the given URL. Note that the transport mechanism will not pass the var1 in the URL string, because we have selected the POST method.

iehttp1.RequestMethod := 'POST';
iehttp1.ExecuteURL('http://www.myserver.com/script1.php?var1=1');

Important note: default vars always use the default request method

3. Post using variables in both the URL and POST contexts

This example will actually post the put_this_on_the_url variable on the url, and var1 on the POST context. The reason is that by selecting POST any default variables passed, that are not explicitly defined as "get variables" are posted normally.

iehttp1.RequestMethod := 'POST';
iehttp1.GetStr := 'put_this_on_the_url=1';
iehttp1.ExecuteURL('http://www.myserver.com/script1.php?var1=1');


4a. Multipart Post

This example will post var1, var2 and var2 in a multipart form. Multipart allows for the submission of huge contents for example texts. To submit binary content see examples 4b and 4c

iehttp1.RequestMethod := 'POST'; //not necessary since the next line will default to POST
iehttp1.MultipartPOST := true;   //this will also set request method to post
iehttp1.PostStr := 'var2=2';
iehttp1.AddMultipartVar('var3' , '3');
iehttp1.ExecuteURL('http://www.myserver.com/script1.php?var1=1');


5. HTTP(S) Authorization

The following example will retrieve a page from a web server that is configured to require HTTP(S) authentication..

iehttp1.username := 'user1';
iehttp1.password := '*****';
iehttp1.ExecuteURL('https://www.myserver.com/index.php');


6a. File Upload - Binary (Standard HTTP Form Upload)

This example will post the image "c:\image1.jpg" to the server, where it will be handled by a php/aspx script.

iehttp1.MultipartPOST := true; //this will also set request method to post
iehttp1.AddMultipartFormFile('file1' , 'c:\image1.jpg');
iehttp1.ExecuteURL('http://www.myserver.com/upload_handler.php');

 

Sample PHP handler script:

<?php
$file1 = $_FILES['file1'];

$target_path = "uploads";
@mkdir($target_path);

$target_fn = $target_path . "/" . basename($file1['name']);

if(move_uploaded_file($file1['tmp_name'], $target_fn)) {
  print "The file ". basename( $file1['name']). " has been uploaded";
} else{
  print "Could not upload file";
}
?>

Sample .NET ASPX handler script:

<%
string upload_dir = Server.MapPath(@"uploads\");
if (!System.IO.Directory.Exists(upload_dir))
  System.IO.Directory.CreateDirectory(upload_dir);

string fn = upload_dir + Request.Files[0].FileName;
Request.Files[0].SaveAs(fn);
%>

 

6b. File Upload - Base 64 (Non standard)

This example will post the image "c:\image1.jpg" to the server, where it will be handled by a php/aspx script. Note that using this non-standard method, the filename is not being transferred. If you will need to transfer the filename you can do it using another variable.

iehttp1.MultipartPOST := true; //this will also set request method to post
iehttp1.AddMultipartVar('filename' , 'image1.jpg');
iehttp1.AddMultipartFile('file_contents_b64' , 'c:\image1.jpg');
iehttp1.ExecuteURL('http://www.myserver.com/upload_handler.php');
 

Sample PHP handler script:

<?php
$filename = $_POST["filename"];
$file_contents_b64 = $_POST["file_contents_b64"];

//decode the base64 encoded variable
$file_contents_binary = base64_decode($file_contents_b64);

//make sure you have write permissions in this folder
$fp = fopen($filename, "w");
fwrite($fp, $file_contents_binary);
fclose($fp);

//that's it
?>

Sample .NET ASPX handler script:

<%
string file_contents_b64 = Request["file_contents_b64"];
byte[] file_contents_binary = Convert.FromBase64CharArray(
    file_contents_b64.ToCharArray(), 0, file_contents_b64.Length);

string filename = Request["filename"];

string upload_dir = Server.MapPath(@"uploads\");
if (!System.IO.Directory.Exists(upload_dir))
  System.IO.Directory.CreateDirectory(upload_dir);

string fn = upload_dir + filename;

//write the file
using (System.IO.FileStream fs = new System.IO.FileStream(fn,                   System.IO.FileMode.CreateNew)) {
  using (System.IO.BinaryWriter writer = new System.IO.BinaryWriter(fs)) {
    writer.Write(file_contents_binary);
  }
}

%>

 

7. Download a file

This will download an image from a web location and save it to disk.

iehttp1.ExecuteURL('http://www.myserver.com/image1.jpg');
iehttp1.result_ms.SaveToFile('c:\image1.jpg');

If you want feedback on the download progress add a TLabel component on a form and add this code on the OnPacketRead event

label1.Caption := iehttp1.GetStringPercentage;
 

8. More examples

Examples 1a and 1b are identical. Var1 will be a POST variable rather than a GET one.

example 1a

iehttp1.RequestMethod := 'POST';
iehttp1.ExecuteURL('http://www.myserver.com/script1.php?var1=1');
//default variables always use the default request method

example 1b

iehttp1.RequestMethod := 'POST';
iehttp1.PostStr := 'var1=1';
iehttp1.ExecuteURL('http://www.myserver.com/script1.php');


---

Examples 2a and 2b are also identical. Var1 will be a GET variable rather than a POST one.

example 2a:

iehttp1.RequestMethod := 'GET'; //optional
iehttp1.ExecuteURL('http://www.myserver.com/script1.php?var1=1');

example 2b:

iehttp1.RequestMethod := 'GET'; //optional
iehttp1.GetStr := 'var1=1';
iehttp1.ExecuteURL('http://www.myserver.com/script1.php');

---

Examples 3a, 3b and 3c are also identical. Var1 will be a multipart POST variable rather than a urlencoded POST one.

example 3a:

iehttp1.RequestMethod := 'POST'; //not necessary
iehttp1.MultipartPOST := true;  //this will also set request method to post
iehttp1.ExecuteURL('http://www.myserver.com/script1.php?var1=1');

example 3b:

iehttp1.MultipartPOST := true; //will also set request method to post
iehttp1.PostStr := 'var1=1';
iehttp1.ExecuteURL('http://www.myserver.com/script1.php');

Example 3c:

iehttp1.MultipartPOST := true; //will also set request method to post
iehttp1.AddMultipartVar('var1' , '1');
iehttp1.ExecuteURL('http://www.myserver.com/script1.php');

 

Change Log:

build 62: 24/Apr/2008
 - unicode improvements
 - automatic detection of UTF-8, UTF-16 and ANSI encodings
 - allows uploading binary files, without the need for Base64-Encoding

build 48: 22/Oct/2006
 - added support for ie7

build 46: 14/Nov/2005
 -fixed onpacketread in non-blocking mode
 -added onTimer event and timerIntervalSeconds property
 
build 44: 03/Sep/2004
 - fixed some bugs in the timout/onpacketread mechanism
 - basic proxy authentication support
 - request_header property e.g. if you want to set "Referer:"
 
build 43: 11/Aug/2004
- fixed bug that was not allowing postStr, getStr to be set.
 
build 42: 17/Jun/2004
- fixed bug that avoids you to reuse the component after a timeout or a cancel request
 
build 41: 18/May/2004
- fixed bug introduced in build 40
 
build 40 : 17/May/2004
- added non-blocking mode
- added method CancelRequest
- added timeout property
- fixed several memory leaks
 
build 27: added http_agent_string variable.
 
build 26: added support for streams and/or files uploading.
 
build 25: added a cookies and response_headers TStringList's.
 



24-Apr-2008 12:12 - 0 comments - add comment

You are not logged in

Login  | Register >>

Username:
Password:

Forgot password
Register>> if you do not have an account yet

by registering you have access to all areas, you can track down unread messages and much more.

 

table_quotes not found or malformed


  MYFXBOARD   .COM    Copyright © 2008-2008 MyFXBoard    |0|DJCPRFQXFRBCQABICMFH
 [myfxboard.com]