-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathSimpleHttpClient.cpp
More file actions
76 lines (61 loc) · 2.61 KB
/
Copy pathSimpleHttpClient.cpp
File metadata and controls
76 lines (61 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
* Copyright 2017 Sony Corporation
*/
#include <iostream>
#include <stdexcept>
#include "easyhttpcpp/EasyHttp.h"
void displayUsage(char** argv)
{
std::cout << "Usage: " << argv[0] << " <url>" << std::endl;
std::cout << " Fetches the resource identified by <url> and prints it to the standard output"
<< std::endl;
}
void dumpResponse(easyhttpcpp::Response::Ptr pResponse)
{
std::cout << "Http status code: " << pResponse->getCode() << std::endl;
std::cout << "Http status message: " << pResponse->getMessage() << std::endl;
std::cout << "Http response headers:\n" << pResponse->getHeaders()->toString() << std::endl;
// dump response body if text
const std::string contentType = pResponse->getHeaderValue("Content-Type", "");
if (Poco::isubstr<std::string>(contentType, "text/html") != std::string::npos) {
std::cout << "Http response body:\n" << pResponse->getBody()->toString() << std::endl;
}
}
int main(int argc, char** argv)
{
// need a url to execute easyhttpcpp http client
if (argc < 2) {
displayUsage(argv);
return 1;
}
std::string url = argv[1];
// HTTP GET the url
std::cout << "HTTP GET url: " << url << std::endl;
try {
// cache dir = current working dir; cache size = 100 KB
easyhttpcpp::HttpCache::Ptr pCache = easyhttpcpp::HttpCache::createCache(Poco::Path::current(), 1024 * 100);
// a default http connection pool
easyhttpcpp::ConnectionPool::Ptr pConnectionPool = easyhttpcpp::ConnectionPool::createConnectionPool();
// configure http cache and connection pool instance (optional but recommended)
easyhttpcpp::EasyHttp::Builder httpClientBuilder;
httpClientBuilder.setCache(pCache)
.setConnectionPool(pConnectionPool);
// create http client
easyhttpcpp::EasyHttp::Ptr pHttpClient = httpClientBuilder.build();
// create a new request and execute synchronously
easyhttpcpp::Request::Builder requestBuilder;
easyhttpcpp::Request::Ptr pRequest = requestBuilder.setUrl(url).build();
easyhttpcpp::Call::Ptr pCall = pHttpClient->newCall(pRequest);
easyhttpcpp::Response::Ptr pResponse = pCall->execute();
if (!pResponse->isSuccessful()) {
std::cout << "HTTP GET Error: (" << pResponse->getCode() << ")" << std::endl;
} else {
std::cout << "HTTP GET Success!" << std::endl;
}
// dump response
dumpResponse(pResponse);
} catch (const std::exception& e) {
std::cout << "Error occurred: " << e.what() << std::endl;
}
return 0;
}