2012-02-22 52 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; 
}