通过openssl库实现https通信,代码样例
时间: 2024-10-24 12:12:55 浏览: 9
thrift通过openssl加密证书实现双向通信
在使用 OpenSSL 库实现 HTTPS 连接时,通常涉及客户端发起 HTTPS 请求的场景。以下是一个简单的 C++ 示例,使用 OpenSSL 来发送 GET 请求到一个服务器:
```cpp
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <string>
#include <iostream>
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cerr << "Usage: ./openssl_http_client URL" << std::endl;
return 1;
}
const char* server_url = argv[1];
SSL_library_init();
SSL_load_error_strings();
// 创建套接字和 SSL 对象
int socket_fd = ::socket(AF_INET, SOCK_STREAM, 0);
SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
// 设置服务器地址
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(443); // HTTPS默认端口
inet_pton(AF_INET, server_url, &addr.sin_addr);
// 打开连接并进行SSL握手
connect(socket_fd, (struct sockaddr*)&addr, sizeof(addr));
SSL *ssl = SSL_new(ctx);
SSL_set_fd(ssl, socket_fd);
SSL_connect(ssl);
// 发送请求
BIO *bio_ssl = BIO_new_socket(socket_fd, BIO_NOCLOSE);
SSL_set_bio(ssl, bio_ssl, bio_ssl);
BIO_set_write_buffer_size(bio_ssl, 8192); // 调整缓冲大小
BIO_write(bio_ssl, "GET / HTTP/1.1\r\nHost: ", strlen("GET / HTTP/1.1\r\nHost: "));
BIO_write(bio_ssl, server_url, strlen(server_url));
BIO_write(bio_ssl, "\r\n", 2);
// 接收响应
char response[4096];
int bytes_received = -1;
while ((bytes_received = SSL_read(ssl, response, sizeof(response))) > 0) {
std::cout.write(response, bytes_received);
}
if (bytes_received < 0) {
ERR_print_errors_fp(stderr);
}
// 关闭连接
SSL_shutdown(ssl);
BIO_free_all(bio_ssl);
SSL_free(ssl);
SSL_CTX_free(ctx);
close(socket_fd);
return 0;
}
```
阅读全文