示例#1
0
文件: http_client.c 项目: ubccr/pcp
static int
http_client_response(http_client *cp)
{
    size_t		bytes;
    char		buffer[BUFSIZ];
    int			sts;
    static int		setup;
    static http_parser_settings	settings;

    if (!setup) {
	memset(&settings, 0, sizeof(settings));
	settings.on_header_field = on_header_field;
	settings.on_header_value = on_header_value;
	settings.on_headers_complete = on_headers_complete;
	settings.on_body = on_body;
	settings.on_message_complete = on_message_complete;
	setup = 1;
    }

    if (pmDebug & DBG_TRACE_HTTP)
	fprintf(stderr, "http_client_response\n");

    http_parser_init(&cp->parser, HTTP_RESPONSE);
    cp->parser.data = (void *)cp;
    cp->error_code = 0;
    cp->offset = 0;

    do {
	if ((sts = __pmRecv(cp->fd, buffer, sizeof(buffer), 0)) <= 0) {
	    http_client_disconnect(cp);
	    return sts ? sts : -EAGAIN;
	}
	bytes = http_parser_execute(&cp->parser, &settings, buffer, sts);

    } while (bytes && !(cp->flags & F_MESSAGE_END));

    if (http_should_client_disconnect(cp))
	http_client_disconnect(cp);

    if (http_should_client_redirect(cp))
	return -EMLINK;

    if (http_should_keep_alive(&cp->parser) == 0)
	http_client_disconnect(cp);

    if (cp->error_code)
	return cp->error_code;

    return cp->offset;
}
示例#2
0
文件: http_client.c 项目: ubccr/pcp
static int
http_client_prepare(http_client *cp, const char *url,
		char *body_buffer, size_t body_length,
		char *type_buffer, size_t type_length)
{
    http_parser_url	parser_url;
    char		*new_url;
    int			sts;

    cp->body_buffer = body_buffer;
    cp->body_length = body_length;
    cp->type_buffer = type_buffer;
    cp->type_length = type_length;

    /* extract individual fields from the given URL */
    http_parser_url_init(&parser_url);
    if ((sts = http_parser_parse_url(url, strlen(url), 0, &parser_url)) != 0) {
	cp->error_code = sts;
	return -1;
    }

    /* short-circuit if we are making a request from a connected server */
    if (http_compare_source(&parser_url, url, &cp->parser_url, cp->url) == 0)
	return 0;
    http_client_disconnect(cp);

    if ((new_url = strdup(url)) == NULL) {
	cp->error_code = -ENOMEM;
	return -1;
    }
    free(cp->url);
    cp->url = new_url;
    cp->parser_url = parser_url;
    return 0;
}
示例#3
0
int main( int argc, char** argv )
{
	if( argc < 4 )
	{
		printf("usage: http_tester [GET,SET,PUT] url path\n");
		return 1;
	}

#if defined( _MSC_VER )
	// Initialize Winsock
	WSADATA wsaData;
	int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
	if (iResult != 0)
	{
		printf("WSAStartup failed: %d\n", iResult);
		return 1;
	}
#endif // defined( _MSC_VER )

    http_client_t c;
    http_client_result res;

    res = http_client_connect( &c, argv[2], 0, 0, 0 );
    HTTP_ERR_CHECK( res );

    if( strcmp( argv[1], "GET" ) == 0 )
    {
		char*  msgbody;
		size_t msgbody_size;
		res = http_client_get( c, argv[3], (void**)&msgbody, &msgbody_size, 0x0 );
		HTTP_ERR_CHECK( res );

		fprintf( stdout, "%.*s\n", (int)msgbody_size, msgbody );
		free( msgbody );
    }
    else if( strcmp( argv[1], "HEAD" ) == 0 )
    {
		size_t msgbody_size;
		res = http_client_head( c, argv[3], &msgbody_size);
		HTTP_ERR_CHECK( res );

		printf( "content size: %lu\n", msgbody_size );
    }

    else if( strcmp( argv[1], "PUT" ) == 0 )
	{
		res = http_client_put( c, argv[3], "apansson", 9 );
		HTTP_ERR_CHECK( res );
	}

    http_client_disconnect( c );
    free( c );

    return 0;
}
/* This is the callback event for HTTP events */
static void event_handler( http_client_t* client, http_event_t event, http_response_t* response )
{
    static uint8_t count = 1; // Keep track of how many responses we have received

    switch( event )
    {
        case HTTP_CONNECTED:
            /* This state is never called */
            break;

        /* This is called when we are disconnected by the server */
        case HTTP_DISCONNECTED:
        {
            connected = WICED_FALSE;
            http_client_disconnect( client ); /* Need to keep client connection state synchronized with the server */
            WPRINT_APP_INFO(( "Disconnected from %s\n", SERVER_HOST ));
            break;
        }

        /* This is called when new data is received (header, or payload) */
        case HTTP_DATA_RECEIVED:
        {
            WPRINT_APP_INFO( ( "------------------ Received response: %d ------------------\n", count ) );

            /* Print Response Header */
            if(response->response_hdr != NULL)
            {
                WPRINT_APP_INFO( ( "----- Response Header: -----\n " ) );
                print_data( (char*) response->response_hdr, response->response_hdr_length );
            }

            /* Print Response Payload  */
            WPRINT_APP_INFO( ("\n----- Response Payload: -----\n" ) );
            print_data( (char*) response->payload, response->payload_data_length );

            if(response->remaining_length == 0)
            {
               WPRINT_APP_INFO( ("\n------------------ End Response %d ------------------\n", count ) );
               http_request_deinit( (http_request_t*) &(response->request) );
               wiced_rtos_set_semaphore(&httpWait); // Set semaphore that allows the next request to start
               count++;
            }
            break;
        }
        default:
        break;
    }
}
示例#5
0
文件: http_client.c 项目: ubccr/pcp
void
pmhttpFreeClient(http_client *cp)
{
    http_client_disconnect(cp);
    free(cp);
}
示例#6
0
文件: http_client.c 项目: ubccr/pcp
static int
http_client_get(http_client *cp)
{
    char		buf[BUFSIZ];
    char		host[MAXHOSTNAMELEN];
    char		*bp = &buf[0], *url = cp->url;
    http_parser_url	*up = &cp->parser_url;
    const char		*path, *agent, *version, *protocol;
    size_t		hostlen, len = 0, length;
    int			sts;


    /* sanitize request parameters */
    if ((agent = cp->user_agent) == NULL)
	agent = pmProgname;
    if ((version = cp->agent_vers) == NULL)
	version = "1.0";
    if ((path = url + up->field_data[UF_PATH].off) == NULL ||
	up->field_data[UF_PATH].off == 0 ||
	strchr(path, '/') == NULL){
	path = "/";	/* assume root-level request */
    }
    hostlen = up->field_data[UF_HOST].len;
    strncpy(host, url + up->field_data[UF_HOST].off, hostlen);
    host[hostlen] = '\0';
    //    strncpy(host, "localhost", sizeof("localhost"));
    //    host[sizeof("localhost")] = '\0';
    //    strncpy(path, "/containers/8d70f8a47a6b6e515fb8e40d31da7928de70e883c235ba16b132e6a3b4f8267d/json", sizeof("/containers/8d70f8a47a6b6e515fb8e40d31da7928de70e883c235ba16b132e6a3b4f8267d/json"));
    //    __pmNotifyErr(LOG_DEBUG, "hit here: %s", cp->type_buffer);
    
    protocol = url + up->field_data[UF_SCHEMA].off;
    length = up->field_data[UF_SCHEMA].len;
    /* prepare and send a GET request */
    if (length == sizeof(HTTP)-1 && strncmp(protocol, UNIX, length) == 0) {
	len += snprintf(bp+len, sizeof(buf)-len, "GET %s HTTP/%s\r\n",
			cp->type_buffer, http_versionstr(cp->http_version));
	len += snprintf(bp+len, sizeof(buf)-len, "Host: %s\r\n", "localhost");
    }
    else
    {
	len += snprintf(bp+len, sizeof(buf)-len, "GET %s HTTP/%s\r\n",
			path, http_versionstr(cp->http_version));
	len += snprintf(bp+len, sizeof(buf)-len, "Host: %s\r\n", host);
    }
    len += snprintf(bp+len, sizeof(buf)-len, "User-Agent: %s/%s\r\n",
			agent, version);
    /* establish persistent connections (default in HTTP/1.1 onward) */
    if (cp->http_version < PV_HTTP_1_1)
	len += snprintf(bp+len, sizeof(buf)-len, "Connection: keep-alive\r\n");
    len += snprintf(bp+len, sizeof(buf)-len, "\r\n");
    buf[BUFSIZ-1] = '\0';

    if ((pmDebug & DBG_TRACE_HTTP) && (pmDebug & DBG_TRACE_DESPERATE))
	fprintf(stderr, "Sending HTTP request:\n\n%s\n", buf);

    if ((sts = __pmSend(cp->fd, buf, len, 0)) < 0) {
	if (__pmSocketClosed()) {
	    sts = 1;
	} else {
	    cp->error_code = sts;
	    sts = -1;
	}
	http_client_disconnect(cp);
    } else {
	sts = 0;
    }

    if (pmDebug & DBG_TRACE_HTTP)
	fprintf(stderr, "http_client_get sts=%d\n", sts);

    return sts;
}
void application_start( void )
{
    wiced_ip_address_t  ip_address;
    wiced_result_t      result;

    /* We need three headers - host, content type, and content length */
    http_header_field_t header[3];
    /* Header 0 is the Host header */
    header[0].field        = HTTP_HEADER_HOST;
    header[0].field_length = strlen( HTTP_HEADER_HOST );
    header[0].value        = SERVER_HOST;
    header[0].value_length = strlen( SERVER_HOST );
    /* Header 1 is the content type (JSON) */
    header[1].field        =  HTTP_HEADER_CONTENT_TYPE;
    header[1].field_length = strlen( HTTP_HEADER_CONTENT_TYPE );
    header[1].value        = "application/json";
    header[1].value_length = strlen( "application/json" );
    /* Header 2 is the content length. In this case, it is the length of the JSON message */
    sprintf(json_len,"%d", strlen(JSON_MSG)); /* Calculate the length of the JSON message and store the value as a string */
    header[2].field        = HTTP_HEADER_CONTENT_LENGTH;
    header[2].field_length = strlen( HTTP_HEADER_CONTENT_LENGTH );
    header[2].value        = json_len; // This holds the length of the JSON message as a sting containing the decimal value
    header[2].value_length = strlen( json_len ); // This is the length of the string that holds the JSON message size. For example, if the JSON is 12 characters, this would be "2" because the string "12" is 2 characters long.

    wiced_init( );

    /* This semaphore will be used to wait for one request to finish before re-initializing and starting the next one */
    wiced_rtos_init_semaphore(&httpWait);

    wiced_network_up(WICED_STA_INTERFACE, WICED_USE_EXTERNAL_DHCP_SERVER, NULL);

    WPRINT_APP_INFO( ( "Resolving IP address of %s\n", SERVER_HOST ) );
    wiced_hostname_lookup( SERVER_HOST, &ip_address, DNS_TIMEOUT_MS, WICED_STA_INTERFACE );
    WPRINT_APP_INFO( ( "%s is at %u.%u.%u.%u\n", SERVER_HOST,
                                                 (uint8_t)(GET_IPV4_ADDRESS(ip_address) >> 24),
                                                 (uint8_t)(GET_IPV4_ADDRESS(ip_address) >> 16),
                                                 (uint8_t)(GET_IPV4_ADDRESS(ip_address) >> 8),
                                                 (uint8_t)(GET_IPV4_ADDRESS(ip_address) >> 0) ) );

    /* Initialize client */
    http_client_init( &client, WICED_STA_INTERFACE, event_handler, NULL );
    client.peer_cn = NULL; /* If you set hostname, library will make sure subject name in the server certificate is matching with host name you are trying to connect. Pass NULL if you don't want to enable this check */

    /* Connect to the server */
    if ( ( result = http_client_connect( &client, (const wiced_ip_address_t*)&ip_address, SERVER_PORT, HTTP_NO_SECURITY, CONNECT_TIMEOUT_MS ) ) == WICED_SUCCESS )
    {
        connected = WICED_TRUE;
        WPRINT_APP_INFO( ( "Connected to %s\n", SERVER_HOST ) );
    }
    else
    {
        WPRINT_APP_INFO( ( "Error: failed to connect to server: %u\n", result) );
        return; /* Connection failed - exit program */
    }

    /* Send a POST to resource /anything */
    http_request_init( &request, &client, HTTP_POST, "/post", HTTP_1_1 );
    http_request_write_header( &request, &header[0], 3 ); // We need 3 headers
    http_request_write_end_header( &request );
    http_request_write( &request, (uint8_t* ) JSON_MSG, strlen(JSON_MSG)); /* Write the content */
    http_request_flush( &request );

    wiced_rtos_get_semaphore(&httpWait, WICED_WAIT_FOREVER); /* Wait for this request to complete before going on */
    /* Disconnect from the server and deinit since we are done now */
    http_client_disconnect( &client );
    http_client_deinit( &client );
}