0

我有保存/读取 http 标头的代码,但在我的应用程序中,我想设置一个 http 响应标头并将其发送到我的客户端。那么如何为客户端发送的任何请求设置 http 标头响应呢?

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <curl/curl.h>

static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
    int written = fwrite(ptr, size, nmemb, (FILE *)stream);
    return written;
}

int main(void)
{
    CURL *curl_handle;
    static const char *headerfilename = "head.txt";
    FILE *headerfile;
    static const char *bodyfilename = "body.txt";
    FILE *bodyfile;

    curl_global_init(CURL_GLOBAL_ALL);
    /* init the curl session */ 

    curl_handle = curl_easy_init();

    /* set URL to get */ 
    curl_easy_setopt(curl_handle, CURLOPT_URL, "http://google.co.in");

    /* no progress meter please */ 
    curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 1L);

    /* send all data to this function  */ 
    curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_data);

    /* open the files */
    headerfile = fopen(headerfilename,"wb");
    if (headerfile == NULL) {
        curl_easy_cleanup(curl_handle);
        return -1;
    }
    bodyfile = fopen(bodyfilename,"wb");
    if (bodyfile == NULL) {
        curl_easy_cleanup(curl_handle);
        return -1;
    }

    /* we want the headers be written to this file handle */ 
    curl_easy_setopt(curl_handle,   CURLOPT_WRITEHEADER, headerfile);

    /* we want the body be written to this file handle instead of stdout */ 
    curl_easy_setopt(curl_handle,   CURLOPT_WRITEDATA, bodyfile);

    /* get it! */ 
    curl_easy_perform(curl_handle);

    /* close the header file */ 
    fclose(headerfile);

    /* close the body file */ 
    fclose(bodyfile);

    /* cleanup curl stuff */ 
    curl_easy_cleanup(curl_handle);

    return 0;
}
4

1 回答 1

0

正如评论中所说:

libcurl 是一个用于执行 HTTP 请求的客户端库。它不会帮助您实现服务器响应

服务器响应必须由服务器端实现发送,您还没有展示,甚至没有解释它是如何实现的。您不能使用 libcurl 实现服务器端。

于 2013-09-24T15:01:37.223 回答