使用libcurl c ++将响应数据存储在post上的变量中

时间:2014-03-25 08:12:17

标签: php c++ curl libcurl

通过运行file.cpp,curl_easy_perform(curl)将来自file.php的响应打印为“[{”Aid_response“:”1“,”Acd_response“:”2“}]”在终端中。但我怎么能将它存储在变量中?请帮帮我。

我的file.cpp

  #include <iostream>
  #include <stdlib.h>
  #include <stdio.h>
  #include <curl/curl.h>

  using namespace std;
  size_t size = 0;

  int main () { 
  CURL *curl;
  CURLcode res;
  curl_global_init(CURL_GLOBAL_ALL);
  curl = curl_easy_init();
  if(curl) 
  {
    curl_easy_setopt(curl, CURLOPT_URL, "http://localhost/file.php");
    string out = "Aid=1&Acd=2";
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, out.c_str());
    res = curl_easy_perform(curl);
    if(res != CURLE_OK)
      fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
    curl_easy_cleanup(curl);
  }
  curl_global_cleanup();
  return 0;
  }

我的file.php

<?php
$Aid = $_REQUEST['Aid'];
$Acd = $_REQUEST['Acd'];
$data = array();
$data[] = array('Aid_response'=> $Aid, 'Acd_response'=> $Acd);
echo json_encode($data);
?>

1 个答案:

答案 0 :(得分:1)

我使用CURLOPT_WRITEFUNCTION存储对变量的响应,现在它正常工作。

这是file.cpp

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <curl/curl.h>

using namespace std;
size_t size = 0;

size_t write_to_string(void *ptr, size_t size, size_t count, void *stream) {
  ((string*)stream)->append((char*)ptr, 0, size*count);
  return size*count;
}
  int main () {
  CURL *curl;
  CURLcode res;
  curl_global_init(CURL_GLOBAL_ALL);
  curl = curl_easy_init();
  if(curl) 
  {
    string out = string("http://localhost/canvas1/flix2.php?Aid=1&Acd=2");
    curl_easy_setopt(curl, CURLOPT_URL, out.c_str());
    string response;
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_to_string);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
    res = curl_easy_perform(curl);
    cout << "Variable response : " << response;
    if(res != CURLE_OK)
      fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
    curl_easy_cleanup(curl);
  }
  curl_global_cleanup();
return 0;
}