我找到了以下代码片段,并对json数据发布到re_url进行了一些更改。但它显示错误连接错误...服务器在8888端口上侦听json数据。
#include <stdio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/bio.h>
#define APIKEY "YOUR_API_KEY"
#define HOST "https://YOUR_WEB_SERVER_URI"
#define PORT "8888"
char *s = "somejson";
int main() {
//
// Initialize the variables
//
BIO* bio;
SSL* ssl;
SSL_CTX* ctx;
//
// Registers the SSL/TLS ciphers and digests.
//
// Basically start the security layer.
//
SSL_library_init();
//
// Creates a new SSL_CTX object as a 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);
//
// Use the variable from the beginning of the file to create a
// string that contains the URL to the site that you want to connect
// to while also specifying the port.
//
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");
}
//
// The bare minimum to make 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 writes here
//
if(!BIO_should_retry(bio))
{
// Not worth implementing, but worth knowing.
}
//
// -> Let us know about the failed writes
//
printf("Failed write\n");
}
//
// Variables used to read the response from the server
//
int size;
char buf[1024];
//
// Read the response message
//
for(;;)
{
//
// Get chunks of the response 1023 at the time.
//
size = BIO_read(bio, buf, 1023);
//
// If no more data, then exit the loop
//
if(size <= 0)
{
break;
}
//
// Terminate the string with a 0, to let know C when the string
// ends.
//
buf[size] = 0;
//
// -> Print out the response
//
printf("%s", buf);
}
//
// Clean after ourselves
//
BIO_free_all(bio);
SSL_CTX_free(ctx);
return 0;
}
上面的代码将详细说明如何与远程服务器建立TLS连接。
重要说明:此代码不检查公钥是否由有效授权机构签名。意思是我不使用根证书进行验证。不要忘记执行此检查,否则您不知道您是否正在连接正确的网站
当涉及到请求本身时。它只不过是手工编写HTTP请求。
您还可以在此链接下找到有关如何在系统中安装openSSL以及如何编译代码以使其使用安全库的说明。
答案 0 :(得分:0)
BIO_set_conn_hostname()使用字符串名称来设置主机名。该 hostname可以是IP地址。主机名还可以包括端口 以hostname:port的形式。使用表格也是可以接受的 &#34;主机名/任何/其他/路径&#34;或&#34;主机名:port / any / other / path&#34;。
您没有提供有效的主机名:
#define HOST "https://YOUR_WEB_SERVER_URI"
...
// Use the variable from the beginning of the file to create a
// string that contains the URL to the site that you want to connect
// to while also specifying the port.
BIO_set_conn_hostname(bio, HOST ":" PORT);
注释正确引用了一个URL,但您提供的URI很可能是错误的。
如果用真实主机名替换YOUR_WEB...
,它仍然是URI而不是主机名。
尝试删除"https://"
部分,仅提供主机名。