## GConnHttp GConnHttp — HTTP connection object |

## Synopsis

                GConnHttp;
    enum        GConnHttpMethod;
    enum        GConnHttpError;
    enum        GConnHttpEventType;
                GConnHttpEvent;
                GConnHttpEventResolved;
                GConnHttpEventResponse;
                GConnHttpEventRedirect;
                GConnHttpEventData;
                GConnHttpEventError;
    void        (*GConnHttpFunc)                (GConnHttp *conn,
                                                 GConnHttpEvent *event,
                                                 gpointer user_data);
    enum        GConnHttpHeaderFlags;
    GConnHttp*  gnet_conn_http_new              (void);
    gboolean    gnet_conn_http_set_uri          (GConnHttp *conn,
                                                 const gchar *uri);
    gboolean    gnet_conn_http_set_header       (GConnHttp *conn,
                                                 const gchar *field,
                                                 const gchar *value,
                                                 GConnHttpHeaderFlags flags);
    void        gnet_conn_http_set_max_redirects
                                                (GConnHttp *conn,
                                                 guint num);
    void        gnet_conn_http_set_timeout      (GConnHttp *conn,
                                                 guint timeout);
    gboolean    gnet_conn_http_set_user_agent   (GConnHttp *conn,
                                                 const gchar *agent);
    gboolean    gnet_conn_http_set_method       (GConnHttp *conn,
                                                 GConnHttpMethod method,
                                                 const gchar *post_data,
                                                 gsize post_data_len);
    void        gnet_conn_http_run_async        (GConnHttp *conn,
                                                 GConnHttpFunc func,
                                                 gpointer user_data);
    gboolean    gnet_conn_http_run              (GConnHttp *conn,
                                                 GConnHttpFunc func,
                                                 gpointer user_data);
    gboolean    gnet_conn_http_steal_buffer     (GConnHttp *conn,
                                                 gchar **buffer,
                                                 gsize *length);
    void        gnet_conn_http_cancel           (GConnHttp *conn);
    void        gnet_conn_http_delete           (GConnHttp *conn);
    gboolean    gnet_http_get                   (const gchar *url,
                                                 gchar **buffer,
                                                 gsize *length,
                                                 guint *response);

## Description

A GConnHttp represents a HTTP client connection. A GConnHttp is created directly by calling `gnet_conn_http_new()`. After that set the URI to retrieve using `gnet_conn_http_set_uri()`. A connection is made and the HTTP request sent only once either `gnet_conn_http_run_async()` or `gnet_conn_http_run()` is called. Use the asynchroneous variant if you want the function to return immediately and prefer to receive data and status information in the background via the callback function. `gnet_conn_http_run_async()` assumes that there is already a GLib main loop running (e.g. the Gtk main loop).

You can decide for yourself how much information you would like to receive during the HTTP operation. All status information is communicated to the caller via the optional callback function.

The easiest way to just retrieve some data via HTTP is to use the convenience function `gnet_http_get()`.

Here is a small example how to retrieve a file with the least amount of effort and error checking (this is more or less what `gnet_http_get()` does internally):

Example 1. Simple GConnHttp usage.

    void
    fetch_and_print_url (const gchar *url)
    {
      GConnHttp  *conn;

      conn = gnet_conn_http_new();

      gnet_conn_http_set_uri(conn, url);

      if (gnet_conn_http_run(conn, NULL, NULL))
      {
        gchar *buf;
        gsize  buflen;

        if (gnet_conn_http_steal_buffer(conn, &buf, &buflen))
        {
          g_print ("Received %u bytes of data:\n%s\n", buflen, buf);
          g_free(buf);
        }
      }

      gnet_conn_http_delete(conn);
    }

      ...

      fetch_and_print_url ("http://www.google.com");

      ...

## Details

### GConnHttp

    typedef struct _GConnHttp GConnHttp;

HTTP Connection. The entire GConnHttp struct is opaque and private.

### enum GConnHttpMethod

    typedef enum
    {
     GNET_CONN_HTTP_METHOD_GET,
     GNET_CONN_HTTP_METHOD_POST
    } GConnHttpMethod;

HTTP request method. Use with `gnet_conn_http_set_method()`.

`GNET_CONN_HTTP_METHOD_GET` | HTTP GET method
`GNET_CONN_HTTP_METHOD_POST` | HTTP POST method

### enum GConnHttpError

    typedef enum
    {
     GNET_CONN_HTTP_ERROR_UNSPECIFIED,
     GNET_CONN_HTTP_ERROR_PROTOCOL_UNSUPPORTED,
    } GConnHttpError;

Error codes. Used by GConnHttpEventError. Note that errors by the HTTP server will be communicated to the client via the GConnHttpEventResponse event.

`GNET_CONN_HTTP_ERROR_UNSPECIFIED` | connection error
`GNET_CONN_HTTP_ERROR_PROTOCOL_UNSUPPORTED` | unsupported protocol (ie. not http)

### enum GConnHttpEventType

    typedef enum
    {
     GNET_CONN_HTTP_RESOLVED,           /* resolved host name           */
     GNET_CONN_HTTP_CONNECTED,          /* connected to host            */
     GNET_CONN_HTTP_RESPONSE,           /* got response (incl. headers) */
     GNET_CONN_HTTP_REDIRECT,           /* got redirect                 */
     GNET_CONN_HTTP_DATA_PARTIAL,       /* we got some data             */
     GNET_CONN_HTTP_DATA_COMPLETE,      /* we got all data              */
     GNET_CONN_HTTP_TIMEOUT,            /* the connection timed out     */
     GNET_CONN_HTTP_ERROR,              /* GConnHttp problem            */
    } GConnHttpEventType;

GConnHttp event type.

`GNET_CONN_HTTP_RESOLVED` | the host name has been resolved or host name resolution failed. The event structure will be a GConnHttpEventResolved structure
`GNET_CONN_HTTP_CONNECTED` | the TCP connection to the HTTP server has been established
`GNET_CONN_HTTP_RESPONSE` | the HTTP server has sent a response and response headers. The event structure will be a GConnHttpEventResponse structure
`GNET_CONN_HTTP_REDIRECT` | the HTTP server has sent a redirect response. The event structure will be a GConnHttpEventRedirect structure
`GNET_CONN_HTTP_DATA_PARTIAL` | data has been received. The buffer is caller-owned (ie. owned by GNet), but may be emptied using `gnet_conn_http_steal_buffer()`. The event structure will be a GConnHttpEventData structure
`GNET_CONN_HTTP_DATA_COMPLETE` | data has been received in full. The buffer is caller-owned (ie. owned by GNet), but may be emptied using `gnet_conn_http_steal_buffer()`. The event structure will be a GConnHttpEventData structure
`GNET_CONN_HTTP_TIMEOUT` | the connection timed out
`GNET_CONN_HTTP_ERROR` | GConnHttp problem (not a server error response). The event structure will be a GConnHttpEventError structure

### GConnHttpEvent

    typedef struct {
     GConnHttpEventType   type;           /* type of event (see above)         */
    } GConnHttpEvent;

GConnHttp Base Event. Check event->type and then cast the event structure into the corresponding specialised event structure.

GConnHttpEventType `type`; | event type

### GConnHttpEventResolved

    typedef struct {
     GInetAddr           *ia;             /* GInetAddr of the host name        */
    } GConnHttpEventResolved;

GConnHttp Host Name Resolved Event. Emitted when the host name has been resolved to an IP address, primarily to give progress feedback to the user. `ia` will be NULL if the host name could not be resolved.

GInetAddr *`ia`; | a GInetAddr of the resolved host name.

### GConnHttpEventResponse

    typedef struct {
     guint                response_code;  /* response code, e.g. 200, or 404   */
     gchar              **header_fields;  /* NULL-terminated array of strings  */
     gchar              **header_values;  /* NULL-terminated array of strings  */
    } GConnHttpEventResponse;

Emitted when the server has sent a response and response headers.

guint `response_code`; | response code from the HTTP server (e.g. 200 or 404)
gchar **`header_fields`; | array of header field strings, NULL-terminated
gchar **`header_values`; | array of header value strings, NULL-termintaed

### GConnHttpEventRedirect

    typedef struct {
     guint                num_redirects;  /* number of redirects so far        */
     guint                max_redirects;  /* max. num. of redirects allowed    */
     gchar               *new_location;   /* redirect location if provided     */
     gboolean             auto_redirect;  /* FALSE if action is needed         */
    } GConnHttpEventRedirect;

Emitted when the server sends a redirect response.

guint `num_redirects`; | number of redirects so far
guint `max_redirects`; | maximum number of redirects allowed
gchar *`new_location`; | redirect location, or NULL if not provided
gboolean `auto_redirect`; | FALSE if action by the client is needed. Set to FALSE to prevent automatic redirection

### GConnHttpEventData

    typedef struct {
     guint64              content_length; /* set if available, otherwise 0     */
     guint64              data_received;  /* bytes received so far             */
     const gchar         *buffer;         /* buffer                            */
     gsize                buffer_length;  /* buffer length                     */
    } GConnHttpEventData;

Emitted when data has been received. Useful for progress feedback to the user or to process data before all of it has been received. The client is responsible for emptying the buffer regularly when the amount of data received or expected is larger than the amount that should be kept in memory (e.g. in the case of large binary files).

guint64 `content_length`; | set if available, otherwise 0
guint64 `data_received`; | total amount of data received so far
const gchar *`buffer`; | buffer with data received so far. Use `gnet_conn_http_steal_buffer()` to empty the buffer.
gsize `buffer_length`; | buffer length

### GConnHttpEventError

    typedef struct {
     GConnHttpError       code;           /* error code                        */
     gchar               *message;        /* message (use for debugging only)  */
    } GConnHttpEventError;

Emitted when an error has occured. Note that HTTP server errors are communicated to the client by means of a GConnHttpEventResponse event.

GConnHttpError `code`; | one of the GConnHttpError codes
gchar *`message`; | clear-text error message (for debugging purposes only)

### GConnHttpFunc ()

    void        (*GConnHttpFunc)                (GConnHttp *conn,
                                                 GConnHttpEvent *event,
                                                 gpointer user_data);

Callback for GConnHttp.

Check event->type and then cast the event into the appropriate event structure. event->type will be one of

`GNET_CONN_HTTP_RESOLVED`: this event occurs when the host name has been resolved or host name resolution failed

`GNET_CONN_HTTP_CONNECTED`: the TCP connection to the HTTP server has been established

`GNET_CONN_HTTP_RESPONSE`: the HTTP server has sent a response and response headers

`GNET_CONN_HTTP_REDIRECT`: the HTTP server has sent a redirect response

`GNET_CONN_HTTP_DATA_PARTIAL`: data has been read. The buffer is caller-owned (ie. owned by GNet), but may be truncated to zero length using the appropriate GString methods. You must not free the buffer

`GNET_CONN_HTTP_DATA_COMPLETE`: data has been received in full. The buffer is caller-owned, but may be truncated to zero length using the appropriate GString methods. You must not free the buffer

`GNET_CONN_HTTP_TIMEOUT`: the connection timed out

`GNET_CONN_HTTP_ERROR`: GConnHttp problem (not a server error response)

`conn` : | GConnHttp
`event` : | event (caller-owned, do not free)
`user_data` : | user data specified in `gnet_conn_http_run()` or `gnet_conn_http_run_async()`

### enum GConnHttpHeaderFlags

    typedef enum
    {
      GNET_CONN_HTTP_FLAG_SKIP_HEADER_CHECK  = 1
    } GConnHttpHeaderFlags;

Flags for `gnet_conn_http_set_header()`.

`GNET_CONN_HTTP_FLAG_SKIP_HEADER_CHECK` | do not check whether the header is a standard header

### gnet_conn_http_new ()

    GConnHttp*  gnet_conn_http_new              (void);

Creates a GConnHttp.

Returns : | a GConnHttp.

### gnet_conn_http_set_uri ()

    gboolean    gnet_conn_http_set_uri          (GConnHttp *conn,
                                                 const gchar *uri);

Sets the URI to GET or POST, e.g. http://www.google.com

`conn` : | a GConnHttp
`uri` : | URI string
Returns : | TRUE if the URI has been accepted.

### gnet_conn_http_set_header ()

    gboolean    gnet_conn_http_set_header       (GConnHttp *conn,
                                                 const gchar *field,
                                                 const gchar *value,
                                                 GConnHttpHeaderFlags flags);

Set header field to send with the HTTP request.

`conn` : | a GConnHttp
`field` : | a header field, e.g. "Accept"
`value` : | the header field value, e.g. "text/html"
`flags` : | one or more flags of GConnHttpHeaderFlags, or 0
Returns : | TRUE if the header field has been set or changed

### gnet_conn_http_set_max_redirects ()

    void        gnet_conn_http_set_max_redirects
                                                (GConnHttp *conn,
                                                 guint num);

Sets the maximum allowed number of automatic redirects. Note that the HTTP protocol specification (RFC2616) specifies occasions where the client must not redirect automatically without user intervention. In those cases, no automatic redirect will be performed, even if the limit has not been reached yet.

`conn` : | a GConnHttp
`num` : | the maximum number of allowed automatic redirects

### gnet_conn_http_set_timeout ()

    void        gnet_conn_http_set_timeout      (GConnHttp *conn,
                                                 guint timeout);

Sets a timeout on the http connection.

`conn` : | a GConnHttp
`timeout` : | timeout in milliseconds

### gnet_conn_http_set_user_agent ()

    gboolean    gnet_conn_http_set_user_agent   (GConnHttp *conn,
                                                 const gchar *agent);

Convenience function. Wraps `gnet_conn_http_set_header()`.

`conn` : | a GConnHttp
`agent` : | the user agent string to send
Returns : | TRUE if the user agent string has been changed.

### gnet_conn_http_set_method ()

    gboolean    gnet_conn_http_set_method       (GConnHttp *conn,
                                                 GConnHttpMethod method,
                                                 const gchar *post_data,
                                                 gsize post_data_len);

Sets the HTTP request method. Default is the GET method.

`conn` : | a GConnHttp
`method` : | a GConnHttpMethod
`post_data` : | post data to send with POST method, or NULL
`post_data_len` : | the length of the post data to send with POST method, or 0
Returns : | TRUE if the method has been changed successfully.

### gnet_conn_http_run_async ()

    void        gnet_conn_http_run_async        (GConnHttp *conn,
                                                 GConnHttpFunc func,
                                                 gpointer user_data);

Starts connecting and sending the specified http request. Will return immediately. Assumes there is an existing and running default Gtk/GLib/Gnome main loop.

`conn` : | a GConnHttp
`func` : | callback function to communicate progress and errors, or NULL
`user_data` : | user data to pass to callback function, or NULL

### gnet_conn_http_run ()

    gboolean    gnet_conn_http_run              (GConnHttp *conn,
                                                 GConnHttpFunc func,
                                                 gpointer user_data);

Starts connecting and sending the specified http request. Will return once the operation has finished and either an error has occured, or the data has been received in full. This function will run its own main loop in the default GLib main context.

`conn` : | a GConnHttp
`func` : | callback function to communicate progress and errors, or NULL
`user_data` : | user data to pass to callback function, or NULL
Returns : | TRUE if no error occured befor connecting

### gnet_conn_http_steal_buffer ()

    gboolean    gnet_conn_http_steal_buffer     (GConnHttp *conn,
                                                 gchar **buffer,
                                                 gsize *length);

Empties the current buffer and returns the contents. The main purpose of this function is to make it possible to just use `gnet_conn_http_run()`, check its return value, and then get the buffer data without having to install a callback function. Also needed to empty the buffer regularly while receiving large amounts of data.

The caller (you) needs to free the buffer with `g_free()` when done.

`conn` : | a GConnHttp
`buffer` : | where to store a pointer to the buffer data
`length` : | where to store the length of the buffer data
Returns : | TRUE if buffer and length have been set

### gnet_conn_http_cancel ()

    void        gnet_conn_http_cancel           (GConnHttp *conn);

Cancels the current http transfer (if any) and makes `gnet_conn_http_run()` return immediately. Will do nothing if the transfer was started with `gnet_conn_http_run_async()`.

`conn` : | a GConnHttp

### gnet_conn_http_delete ()

    void        gnet_conn_http_delete           (GConnHttp *conn);

Deletes a GConnHttp and frees all associated resources.

`conn` : | a GConnHttp

### gnet_http_get ()

    gboolean    gnet_http_get                   (const gchar *url,
                                                 gchar **buffer,
                                                 gsize *length,
                                                 guint *response);

Convenience function that just retrieves the provided URI without the need to set up a full GConnHttp. Uses `gnet_conn_http_run()` internally.

Caller (you) needs to free the buffer with `g_free()` when no longer needed.

`url` : | a URI, e.g. http://www.foo.com
`buffer` : | where to store a pointer to the data retrieved
`length` : | where to store the length of the data retrieved
`response` : | where to store the last HTTP response code received from the HTTP server, or NULL.
Returns : | TRUE if `buffer`, `length` and `response` are set, otherwise FALSE.