HTTP request header from client
GET / HTTP/1.1 Host: www.baidu.com Conection: Close
HTTP receive content from website
HTTP/1.1 200 OK Date: Tue, 20 Dec 2016 06:41:33 GMT Content-Type: text/html; charset=utf-8 Transfer-Encoding: chunked Connection: Close Vary: Accept-Encoding Set-Cookie: BAIDUID=6D9997D7BF91EA2006DB0AE36807035E:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com Set-Cookie: BIDUPSID=6D9997D7BF91EA2006DB0AE36807035E; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com Set-Cookie: PSTM=1482216093; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com Set-Cookie: BDSVRTM=0; path=/ Set-Cookie: BD_HOME=0; path=/ Set-Cookie: H_PS_PSSID=1458_21106_18560_17001_21553_21617; path=/; domain=.baidu.com P3P: CP=" OTI DSP COR IVA OUR IND COM " Cache-Control: private Cxy_all: baidu+1e84b469cab50e970cc4de4762794ece Expires: Tue, 20 Dec 2016 06:41:32 GMT X-Powered-By: HPHP Server: BWS/1.1 X-UA-Compatible: IE=Edge,chrome=1 BDPAGETYPE: 1 BDQID: 0xdac8a3ac0000895d BDUSERID: 0 ...
client.c
#include <glib.h>
#include <gio/gio.h>
#include <string.h>
int main(int argc, char *argv[])
{
gchar *url = "www.baidu.com";
guint port = 80;
GError *error = NULL;
GString *req = NULL;
gchar buffer[1024];
gssize rs;
gchar *name = "/";
req = g_string_new("GET ");
req = g_string_append(req, name);
req = g_string_append(req, " HTTP/1.1\r\nHost: ");
req = g_string_append(req, url);
req = g_string_append(req, "\r\nUser-Agent:Mozilla/4.0\r\nConnection: Close\r\n\r\n");
/* create a new connection */
GSocketConnection *connection = NULL;
GSocketClient *client = g_socket_client_new();
/* connect to the host */
connection = g_socket_client_connect_to_host(client, url, port, NULL, &error);
/* don't forget to check for errors */
if (error != NULL)
{
g_error(error->message);
}
else
{
g_print("Connection successful!\n");
}
g_object_unref(client);
/* use the connection */
GInputStream *istream = g_io_stream_get_input_stream(G_IO_STREAM(connection));
GOutputStream *ostream = g_io_stream_get_output_stream(G_IO_STREAM(connection));
g_output_stream_write(ostream, req->str, strlen(req->str), NULL, &error);
if (error != NULL)
{
g_error(error->message);
}
else
{
g_print("req:\n%s\n", req->str);
}
g_string_free(req, TRUE);
g_print("recv:\n");
do
{
rs = g_input_stream_read(istream, buffer, 1024, NULL, &error);
if (error != NULL)
{
g_error(error->message);
}
else
{
g_print("%s", buffer);
bzero(buffer,1024);
}
}while (rs > 0);
g_io_stream_close(G_IO_STREAM(connection), NULL, &error);
return 0;
}
makefile
obj = glib_path = /storage/emulated/0/c/glib-2.45-android-core/libglib glib_cflags = -I$(glib_path)/include -I$(glib_path)/include/glib-2.0 -I$(glib_path)/lib/glib-2.0/include glib_libs = -L$(glib_path)/lib -lgio-2.0 -lgobject-2.0 -lgthread-2.0 -lgmodule-2.0 -lglib-2.0 -liconv -lintl -lffi -lz all:client client:client.o $(CC) -o $@ $< $(glib_libs) %.o:%.c $(CC) -c $< -o $@ $(glib_cflags)