如何使用C建立HTTP连接?那里有任何参考或示例代码?此外,如何实现从C编写的客户端打开Comet连接? (关于打开HTTPS连接的任何其他信息也将不胜感激。)谢谢!
答案 0 :(得分:2)
答案 1 :(得分:2)
试试这个,一个很好的参考
以上是套接字编程的教程,您可以使用它们来构建自己的http客户端,否则您可以选择像curl这样的内置库。 如果您使用普通套接字,那么您需要对标头信息进行编码和解码以及每个请求,还需要考虑许多其他关于http协议的因素 http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
答案 2 :(得分:1)
这是一个古老的话题,但肯定是一个谷歌搜索很多。经过我自己研究的几周后,阅读有关这个主题并阅读一些复杂的例子和教程。我把它煮到了使其工作所需的最低限度。
重要说明:此代码不检查公钥是否由有效授权机构签名。含义我不使用根证书进行验证。
下面的代码也是我构建的更大项目的一部分。您可以查看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;
}