C ++ REST SDK Касабланка Client.request

Я хочу написать небольшую программу на С ++, которая отправляет запрос на сервер для получения некоторых данных. Я нашел C ++ Rest-SDK и решил использовать его. Я искал примеры кода на разных сайтах, но многие из них не работают с ошибками синтаксиса. Теперь я получил этот код, но метод client.request пропущен. Программа никогда не запускается. Надеюсь, кто-то может понять проблему и, возможно, объяснить, что я должен изменить.

#include <Windows.h>
#include <iostream>
#include <sstream>
#include <string>
#include "cpprest/containerstream.h"#include "cpprest/filestream.h"#include "cpprest/http_client.h"#include "cpprest/json.h"#include "cpprest/producerconsumerstream.h"#include "cpprest/http_client.h"#include <string.h>
#include <conio.h>

using namespace std;
using namespace web;
using namespace web::json;
using namespace web::http;
using namespace web::http::client;
using namespace utility;
using namespace utility::conversions;int main() {

http_client client(L"http://httpbin.org/ip");

client.request(methods::GET).then([](http_response response)
{
if(response.status_code() == status_codes::OK)
{
auto body = response.extract_string().get();
std::wcout << body;
getch();
}
});return 0;
}

2

Решение

Вполне возможно, что основной поток завершается до выполнения задачи «Запрос», поэтому вы не можете видеть какие-либо результаты консоли. Я предлагаю вам вызвать функцию «wait ()» после «.then», как в ответе на их сайт

4

Другие решения

Ваша программа запускается до конца main и заканчивается. Вам нужно добавить wait после then вызов:

client.request(methods::GET).then([](http_response response)
{
// ...
}).wait();
4

этот код работает:

// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "StdAfx.h"#include <cpprest/http_client.h>
#include <cpprest/filestream.h>

using namespace utility;                    // Common utilities like string conversions
using namespace web;                        // Common features like URIs.
using namespace web::http;                  // Common HTTP functionality
using namespace web::http::client;          // HTTP client features
using namespace concurrency::streams;       // Asynchronous streamsint main(int argc, char* argv[])
{
// Make the request and asynchronously process the response.http_client client(L"http://localhost:8082/TPJAXRS/Test/test");

client.request(methods::GET).then([](http_response response)
{
if(response.status_code() == status_codes::OK)
{
auto body = response.extract_string().get();
std::wcout << body<< std::endl;}});
std::cout << "Hello world!" << std::endl;system("PAUSE");
return 0;}
1

#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
#include <cpprest/http_listener.h>              // HTTP server
#include <cpprest/json.h>                       // JSON library
#include <cpprest/uri.h>                        // URI library
#include <cpprest/ws_client.h>                  // WebSocket client
#include <cpprest/containerstream.h>            // Async streams backed by                    STL containers
#include <cpprest/interopstream.h>              // Bridges for integrating  Async streams with STL and WinRT streams
#include <cpprest/rawptrstream.h>               // Async streams backed by raw pointer to memory
#include <cpprest/producerconsumerstream.h>     // Async streams for producer consumer scenarios
using namespace utility;                    // Common utilities like string conversions
using namespace web;                        // Common features like URIs.
using namespace web::http;                  // Common HTTP functionality
using namespace web::http::client;          // HTTP client features
using namespace concurrency::streams;       // Asynchronous streams
using namespace web::http::experimental::listener;          // HTTP server
using namespace web::experimental::web_sockets::client;     // WebSockets client
using namespace web::json;                                  // JSON library
int main(int argc, char* argv[])
{
auto fileStream = std::make_shared<ostream>();

// Open stream to output file.
pplx::task<void> requestTask =   fstream::open_ostream(U("results.html")).then([=](ostream outFile)
{
*fileStream = outFile;

// Create http_client to send the request.
http_client client(U("http://www.bing.com/"));

// Build request URI and start the request.
uri_builder builder(U("/search"));
builder.append_query(U("q"), U("cpprestsdk github"));
return client.request(methods::GET, builder.to_string());
})

// Handle response headers arriving.
.then([=](http_response response)
{
printf("Received response status code:%u\n", response.status_code());

// Write response body into the file.
return response.body().read_to_end(fileStream->streambuf());
})

// Close the file stream.
.then([=](size_t)
{
return fileStream->close();
});

// Wait for all the outstanding I/O to complete and handle any exceptions
try
{
requestTask.wait();
}
catch (const std::exception &e)
{
printf("Error exception:%s\n", e.what());
}

return 0;
}

Это для настройки в HTTP-запросе

ссылка на учебник HTTP для получения дополнительной информации пройдите этот урок

0
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector