Click or drag to resize

HttpClient Class

The HttpClient class represents a client connection to an HTTP Server. HttpClient will automatically follow redirects. Automatic redirects are configurable via the AllowAutoRedirect property. To specify the maximum number of redirects, change the MaximumAutomaticRedirections property to the desired value.
Inheritance Hierarchy
SystemObject
  Crestron.SimplSharp.NetClient
    Crestron.SimplSharp.Net.HttpHttpClient

Namespace: Crestron.SimplSharp.Net.Http
Assembly: SimplSharpHelperInterface (in SimplSharpHelperInterface.dll) Version: 2.21.121
Syntax
C#
public class HttpClient : Client

The HttpClient type exposes the following members.

Constructors
 NameDescription
Public methodHttpClient Creates a new instance of the HttpClient class.
Top
Properties
 NameDescription
Public propertyAccept Gets or sets content types that are acceptable for the response. The default value is "text/html, image/gif, image/jpeg, image/png, */*".
Public propertyAllowAutoRedirect Gets or sets a value that indicates whether the request should follow redirection responses (HTTP codes from 300 to 399). Default Value: true
Public propertyBindingObsolete.
Obsolete - Please use BindingV4 and BindingV6 instead.
(Inherited from Client)
Public propertyBindingV4 Gets the binding which provides properties and methods such as address family, IPv4 address, port number etc for client to connect to the host network.
(Inherited from Client)
Public propertyBindingV6 Gets the binding which provides properties and methods such as address family, IPv6 address, port number etc for client to connect to the host network.
(Inherited from Client)
Public propertyConnectionClass Use the ConnectionClass property to specify an alternative Connection class to be used for out coming data connections. Existing connections are not affected by changing the property.
(Inherited from Client)
Protected propertyConnectionPool Get or set the Connection Pool for this Client Instance.
(Inherited from Client)
Public propertyCustomConnectionPool Gets or sets the custom connection pool. This property is inherited from the Client class.
Public propertyDnsResolveType Determines if the specified HostName should be looked up only: Once per application run (if you establish multiple connections to the server, the subsequent connections will use the cached IPAddress) or Always, for each connect (the Hostname will be resolved again for each subsequent connect). You'll usually only change this setting off the default (Once) if you anticipate the IPAddress of the target host to change frequently.
(Inherited from Client)
Public propertyEnableNagle Set the property value to true to enable the Nagle algorithm for send coalescing.
(Inherited from Client)
Public propertyHostAddress Gets or sets a Client Host IP Address as a string.
(Inherited from Client)
Public propertyHostName The server host name or IP address that you intend the client to connect to.
(Inherited from Client)
Public propertyKeepAlive Controls whether to use HTTP Keep-Alive to keep the connection alive between requests. If enabled (true) , once a request is made and a connection is established, this connection is kept open and used for future requests. If disabled, the connection is closed, and a new connection is created for future requests.
Public propertyMaximumAutomaticRedirections Gets or sets the maximum number of redirects that the request follows. Default Value: 20
Public propertyPassword Password that will be inserted into the Authorization HTTP header in the request to the server.
Public propertyPort The server Port that you intend the client to connect to.
Remarks
If you do not assign a port number on this property, the port number in the parsed URL will be used.
Remarks
If a port number is assigned in the parsed URL, it will take precedence over this property.

(Inherited from Client)
Public propertyProcessBusy If using commands with callbacks, check this busy flag before using another command (Dispatch, Get, Post, etc.)
Public propertyTimeout Gets or sets the maximum amount of time (in seconds) that a client will wait for a server response within a single request. The default value is 60 seconds (1 minute). The timeout handling can be activated via the TimeoutEnabled property.
Public propertyTimeoutEnabled This property controls whether the request operation will do an automatic timeout checking. If timeout handling is turned on (i.e. this property is set to true) and a request takes longer than Timeout, it will be terminated.
Public propertyUrl Gets or sets the URL of the remote server.
Public propertyUseConnectionPooling Enables or disables connection pooling.
Public propertyUserAgent Gets or sets the identifier of the software being used to retrieve data via the URL. Some custom HTTP servers check this HTTP header to provide content optimized for particular HTTP browsers.
Public propertyUserName Name that will be inserted into the Authorization HTTP header in the request to the server.
Public propertyUserObject Gets the last user specified Object for the Async operations on this HTTP Client instance. The return value will evaluate to null if Async operations with the object parameter are not utilized.
Public propertyVerbose Set Logging to Verbose on/off
Public propertyVersion Gets or sets the version identifier of the UserAgent. Can be used to mimic particular browsers like Internet Explorer 6.0
Top
Methods
 NameDescription
Public methodAbort Closes the currently open connection (if present).
Public methodCode exampleBeginGetRequestStream Begins an asynchronous request for a Stream object to use to write data.
Public methodCode exampleBeginGetResponseStream Begins an asynchronous response for a Stream object to use to read data.
Public methodConnect Connect the client to a remote network host.
(Inherited from Client)
Public methodConnect(String, Int32) Connect to the host address at the specified port.
(Inherited from Client)
Public methodConnectNew Overloaded. Opens and returns new connection with specified host and port.
(Inherited from Client)
Public methodDispatch One of the core methods of the HttpClient class. This method uses the HttpClientRequest class to send messages to the server and the HttpClientResponse to receive server answers. Uses the TryDispatch method to send data and raises an HttpException exception if any errors occurs.
Public methodDispatchAsync Asynchronously dispatch a request and return a response to the specified callback function
Public methodDispatchAsyncEx Asynchronously dispatch a request and return a response to the specified callback function
Public methodDispatchBytesAsync Asynchronously launches the request that returns a byte array
Public methodDispatchBytesAsyncEx Asynchronously launches the request that returns a byte array
Public methodDispatchStringAsync Asynchronously launches the request that returns a string
Public methodDispatchStringAsyncEx Asynchronously launches the request that returns a string
Public methodDispose Disposes the Client Connection.
(Inherited from Client)
Protected methodDispose(Boolean) Disposes of the current instance and releases all resources used by it.
(Overrides ClientDispose(Boolean))
Public methodCode exampleEndGetRequestStream Supply the stream interface
Public methodCode exampleEndGetResponseStream Ends an asynchronous request to an Internet resource
Public methodEqualsDetermines whether the specified object is equal to the current object.
(Inherited from Object)
Public methodFgetFile Gets the file from the server and writes the data to lpath
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.
(Inherited from Object)
Public methodFpostFile Posts the file data to the server from the local machine
Public methodFputFile Puts the file data to the server from the local machine
Public methodGet(String) Retrieves an HTTP document (as a string) from the provided URL using the GET HTTP command.
Public methodGet(String, Encoding) Retrieves an HTTP document (as a string) in the specified encoding from the provided URL using the GET HTTP command.
Public methodGetAsync(String, HTTPClientStringCallback) Asynchronously retrieves an HTTP document from the provided URL using the GET HTTP command.
Public methodGetAsync(String, Encoding, HTTPClientStringCallback) Asynchronously retrieves an HTTP document using a callback in the specified encoding from the provided URL using the GET HTTP command.
Public methodGetAsyncEx(String, HTTPClientStringCallbackEx, Object) Asynchronously retrieves an HTTP document from the provided URL using the GET HTTP command.
Public methodGetAsyncEx(String, Encoding, HTTPClientStringCallbackEx, Object) Asynchronously retrieves an HTTP document using a callback in the specified encoding from the provided URL using the GET HTTP command.
Public methodGetBytes Retrieves binary data from the provided URL.
Public methodGetBytesAsync Asynchronously retrieves binary data from the provided URL using a callback.
Public methodGetBytesAsyncEx Asynchronously retrieves binary data from the provided URL using a callback.
Public methodGetHashCodeServes as the default hash function.
(Inherited from Object)
Protected methodGetHttpConnection This method is used internally to acquire (either create or retrieve from the pool) an HTTP connection with the provided parameters.
Public methodGetResponse This method is used internally by all other Get* methods of this class. It creates and sends a GET HTTP request to the server and returns a response.
Public methodGetResponseAsync Asynchronously creates and sends a GET HTTP request to the server using the callback. A Response is returned.
Public methodGetResponseAsyncEx Asynchronously creates and sends a GET HTTP request to the server using the callback. A Response is returned.
Public methodGetTypeGets the Type of the current instance.
(Inherited from Object)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object.
(Inherited from Object)
Protected methodNewConnection Creates a New Client Connection with the specified binding.
(Inherited from Client)
Public methodPost(String, Stream) Retrieves an HTTP document (as a string) from the provided Url using the POST HTTP command.
Public methodPost(String, Byte) Retrieves an HTTP document (as a string) from the provided URL using the POST HTTP command.
Public methodPostAsync(String, Stream, HTTPClientResponseCallback) Asynchronously retrieves an HTTP document (as a string) from the provided Url using the POST HTTP command.
Public methodPostAsync(String, Byte, HTTPClientStringCallback) Asynchronously retrieves an HTTP document (as a string) from the provided Url using the POST HTTP command.
Public methodPostAsync(String, Byte, HTTPClientStringCallbackEx, Object) Asynchronously retrieves an HTTP document (as a string) from the provided Url using the POST HTTP command.
Public methodPostAsyncEx Asynchronously retrieves an HTTP document (as a string) from the provided Url using the POST HTTP command.
Protected methodReleaseConnection Releases the Connection for the specified connection in the Connection Pool.
(Inherited from Client)
Protected methodRequestDone Request is done being processed.
Protected methodResolveHostName Resolves the host name.
(Inherited from Client)
Protected methodResolveHostNameIfNeeded Determines whether it is necessary to resolve the host name based on the Host Address and DNS resolve type, and then resolves the host name accordingly.
(Inherited from Client)
Public methodToStringReturns a string that represents the current object.
(Inherited from Object)
Protected methodTriggerOnResolvedHostName Trigger the OnResolvedHostName.
(Inherited from Client)
Protected methodTriggerOnResolveHostName Triggers the Resolve
(Inherited from Client)
Top
Events
 NameDescription
Public eventOnResolvedHostName This event is fired after the hostname has been successfully resolved.
(Inherited from Client)
Public eventOnResolveHostName This event is fired before the Client attempts to resolve the specified HostName to an IP address. It provides you with an option to perform the resolution yourself, obtain the IP address from an internal cache you're maintaining, or do some other processing (such as for example changing the hostname to look up).
(Inherited from Client)
Top
Example
This method uses an HttpClient to dispatch an HTTP DELETE request to a URL, then reads the response code
C#
// Send a DELETE request to the specified URL
public void SendDelete(string urlString)
{
    try
    {
        HttpClient client = new HttpClient();
        HttpClientRequest req = new HttpClientRequest();
        UrlParser url = new UrlParser(urlString);
        req.Url = url;
        req.RequestType = RequestType.Delete;

        HttpClientResponse res = client.Dispatch(req);

        if (res.Code == 204) // Expecting a "Not Found" response to show that the DELETE succeeded
        {
            CrestronConsole.PrintLine("DELETE request succeeded");
        }
        else
        {
            CrestronConsole.PrintLine("DELETE request returned unexpected response code: {0}", res.Code);
        }
        res.Dispose();
        client.Dispose();
    }
    catch (Exception e)
    {
        CrestronConsole.PrintLine("Error in SendDelete(): " + e);
    }
}

Version Information

.NET

Supported in: 6.0

.NET Compact Framework

Supported in: 3.5
See Also