首页 > 解决方案 > 带有 HTTP 响应代码的 libcurl 始终为 0?

问题描述

我正在尝试将 libcurl 用于服务器的 http post 方法(PEP 与 PDP 的通信)。

我用 Postman 测试了服务器,它工作正常。

我采用了以下链接中的 curl 示例进行测试:

https://curl.haxx.se/libcurl/c/post-callback.html

我修改了 http 标头以匹配在 Postman 设置中配置的标头。

但是,HTTP 响应代码始终为 0。

以下是我为 curl 运行的代码。

#include <stdio.h>
#include <string.h>
#include <curl/curl.h>

static const char data[]  = "some XACML format";

 ...
int main(void)
{
   CURL *curl;
   CURLcode res;

   struct WriteThis wt;

   wt.readptr = data;
   wt.sizeleft = strlen(data);

   long  http_code= 0;
  /* In windows, this will init the winsock stuff */ 
  res = curl_global_init(CURL_GLOBAL_DEFAULT);
  /* Check for errors */ 
   if(res != CURLE_OK) {
     fprintf(stderr, "curl_global_init() failed: %s\n",
     curl_easy_strerror(res));
     return 1;
      }

  /* get a curl handle */ 
      curl = curl_easy_init();
     if(curl) {
  /* First set the URL that is about to receive our POST. */ 
    curl_easy_setopt(curl, CURLOPT_URL, 
     "http://10.10.150.134:9443/api/identity/entitlement/decision/pdp");

    /* Now specify we want to POST data */ 
    curl_easy_setopt(curl, CURLOPT_POST, 1L);

   /* we want to use our own read function */ 
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);

    /* pointer to pass to our read function */ 
   curl_easy_setopt(curl, CURLOPT_READDATA, &wt);

    /* get verbose debug output please */ 
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);


     struct curl_slist *chunk = NULL;
     chunk =curl_slist_append(chunk, "Accept:*/*");
     chunk =curl_slist_append(chunk, "Authorization:Basic YWRtaW46YWRtaW4=");
     chunk =curl_slist_append(chunk, "Content-Type:application/xml");
     res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);

     curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)wt.sizeleft);
     res = curl_easy_perform(curl);
     res = curl_easy_getinfo(curl,CURLINFO_HTTP_CODE,&http_code);


    if(res != CURLE_OK)
       fprintf(stdout, "curl_easy_perform() failed with HTTP code (%ld): %s\n",
           http_code,curl_easy_strerror(res));
    else {   
       fprintf(stdout, "curl_easy_perform() succeeded with HTTP code (%ld): %s\n",
         http_code,curl_easy_strerror(res));
}
     curl_easy_cleanup(curl);
   }
    curl_global_cleanup();
    return 0;
 }

上述代码的输出始终如下:

Trying 10.10.150.134...

*Connected to 10.10.150.134 (10.10.150.134) port 9443 (#0)

>POST /api/identity/entitlement/decision/pdp HTTP/1.1

Host: 10.10.150.134:9443

Accept:*/*

Authorization:Basic YWRtaW46YWRtaW4=

Content-Type:application/xml

Content-Length: 1018

*We are completely uploaded and fine

*Connection #0 to host 10.10.150.134 left intact

"???"curl_easy_perform() succeeded with HTTP code (0): No error

“???” 是一些公认的字符...但是,HTTP 代码始终为 0。我已经用谷歌搜索了这个,但没有一个解决方案适用于我的情况 :(...

标签: httpauthorizationlibcurlxacmlabac

解决方案


推荐阅读