2012-02-22 122 views
2

如何使用C进行HTTP连接?那里有任何引用或示例代码?此外,我如何实现用C编写的客户端打开Comet连接? (任何有关打开HTTPS连接的其他信息也将不胜感激。)谢谢!如何使用C进行HTTP连接?

+3

您正在寻找[libcurl的(http://curl.haxx.se/)。 – Jon 2012-02-22 08:39:53

回答

1

这是个老话题了许多其他因素有关HTTP协议,但是可以肯定的一个是Google搜索了很多。经过我自己的研究数周后,阅读这个主题,并翻阅一些复杂的例子和教程。我将它简化为使其工作所需的最低限度。

重要注意事项:此代码不检查公钥是否由有效授权机构签署。这意味着我不使用根证书进行验证。

下面的代码也是我构建的一个更大的项目的一部分,您可以查看README.md,听听在哪里可以找到有关如何安装openSSL以及如何编译代码的其他信息。

#include <stdio.h> 
#include <openssl/ssl.h> 
#include <openssl/err.h> 
#include <openssl/bio.h> 

#define APIKEY "YOUR_API_KEY" 
#define HOST "YOUR_WEB_SERVER_URI" 
#define PORT "443" 

int main() { 

    // 
    // Initialize Variables 
    // 
    BIO* bio; 
    SSL* ssl; 
    SSL_CTX* ctx; 

    // 
    // Registers the available SSL/TLS ciphers and digests. 
    // 
    // Basically start the security layer. 
    // 
    SSL_library_init(); 

    // 
    // Creates a new SSL_CTX object as framework to establish TLS/SSL 
    // or DTLS enabled connections 
    // 
    ctx = SSL_CTX_new(SSLv23_client_method()); 

    // 
    // -> Error check 
    // 
    if (ctx == NULL) 
    { 
     printf("Ctx is null\n"); 
    } 

    // 
    // Creates a new BIO chain consisting of an SSL BIO 
    // 
    bio = BIO_new_ssl_connect(ctx); 

    // 
    // uses the string name to set the hostname 
    // 
    BIO_set_conn_hostname(bio, HOST ":" PORT); 

    // 
    // Attempts to connect the supplied BIO 
    // 
    if(BIO_do_connect(bio) <= 0) 
    { 
     printf("Failed connection\n"); 
     return 1; 
    } 
    else 
    { 
     printf("Connected\n"); 
    } 

    // 
    // Data to send to create a HTTP request. 
    // 
    char* write_buf = "POST/HTTP/1.1\r\n" 
         "Host: " HOST "\r\n" 
         "Authorization: Basic " APIKEY "\r\n" 
         "Connection: close\r\n" 
         "\r\n"; 

    // 
    // Attempts to write len bytes from buf to BIO 
    // 
    if(BIO_write(bio, write_buf, strlen(write_buf)) <= 0) 
    { 
     // 
     // Handle failed write here 
     // 
     if(!BIO_should_retry(bio)) 
     { 
      // Not worth implementing, but worth knowing. 
     } 

     // 
     // -> Let us know about the failed write 
     // 
     printf("Failed write\n"); 
    } 

    // 
    // Variables used to read the response from the server 
    // 
    int size; 
    char buf[1024]; 

    // 
    // Read the response message 
    // 
    for(;;) 
    { 
     // 
     // Put response in a buffer of size. 
     // 
     size = BIO_read(bio, buf, 1023); 

     // 
     // If no more data, then exit the loop 
     // 
     if(size <= 0) 
     { 
      break; 
     } 

     // 
     // Terminate the string with a 0 so the system knows where 
     // the end is. 
     // 
     buf[size] = 0; 

     printf("%s", buf); 
    } 

    // 
    // Clean after ourselves 
    // 
    BIO_free_all(bio); 
    SSL_CTX_free(ctx); 

    return 0; 
}