本文整理汇总了C++中HttpClient类的典型用法代码示例。如果您正苦于以下问题:C++ HttpClient类的具体用法?C++ HttpClient怎么用?C++ HttpClient使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HttpClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: g_strdup_printf
void HttpClient::on_connected(gpointer data, bool succeeded)
{
HttpClient *oHttpClient = (HttpClient *)data;
if (!succeeded) {
gchar *mes = g_strdup_printf("Can not connect to %s: %s\n",
oHttpClient->host_.c_str(), Socket::get_error_msg().c_str());
on_error_.emit(oHttpClient, mes);
g_free(mes);
return;
}
#ifdef _WIN32
oHttpClient->channel_ = g_io_channel_win32_new_socket(oHttpClient->sd_);
#else
oHttpClient->channel_ = g_io_channel_unix_new(oHttpClient->sd_);
#endif
g_io_channel_set_encoding(oHttpClient->channel_, NULL, NULL);
/* make sure that the channel is non-blocking */
int flags = g_io_channel_get_flags(oHttpClient->channel_);
flags |= G_IO_FLAG_NONBLOCK;
GError *err = NULL;
g_io_channel_set_flags(oHttpClient->channel_, GIOFlags(flags), &err);
if (err) {
gchar *str = g_strdup_printf("Unable to set the channel as non-blocking: %s", err->message);
on_error_.emit(oHttpClient, str);
g_free(str);
g_error_free(err);
return;
}
if (oHttpClient->SendGetRequest())
return;
oHttpClient->out_source_id_ = g_io_add_watch(oHttpClient->channel_, GIOCondition(G_IO_OUT), on_io_out_event, oHttpClient);
oHttpClient->in_source_id_ = g_io_add_watch(oHttpClient->channel_, GIOCondition(G_IO_IN | G_IO_ERR), on_io_in_event, oHttpClient);
}
示例2: HttpRequest
//HTTP请求
static int HttpRequest(lua_State* pState)
{
lua_settop(pState, 4);
const char* t = luaL_checkstring(pState, 1);
const char* url = luaL_checkstring(pState, 2);
const char* d = lua_tostring(pState, 3);
int luaref = LUA_NOREF;
if (!lua_isnoneornil(pState, 4))
{
luaref = luaL_ref(pState, LUA_REGISTRYINDEX);
}
HTTPMSG* pMsg = XNEW(HTTPMSG)();
pMsg->url = std::string(url);
pMsg->data = std::string(d?d:"");
pMsg->luaref = luaref;
if (strcmp(t, "GET") == 0)
{
goHttpClient.HttpGet(pMsg);
}
else
{
goHttpClient.HttpPost(pMsg);
}
return 0;
}
示例3: run
void SendShake::run(void *ptr)
{
bool *success = reinterpret_cast<bool *>(ptr);
std::stringstream uri;
uri<<"http://d.web2.qq.com/channel/shake2?to_uin="
<<to_uin<<"&clientid="
<<client_id<<"&psessionid="<<psessionid
<<"&t="<<QQUtil::currentTimeMillis();
HttpClient request;
std::list<std::string> headers;
headers.clear();
headers.push_back("Referer: http://d.web2.qq.com/proxy.html?v=20110331002&callback=1&id=2");
request.setHttpHeaders(headers);
std::string result = request.requestServer(uri.str());
Json::Reader jsonReader;
Json::Value root;
jsonReader.parse(result, root, false);
int ret= root["retcode"].asInt();
if ( ret == 0 )
{
*success = true;
}
else
{
*success = false;
}
}
示例4: snprintf
bool TestServer::TestTakeoverServer() {
// start a server
snprintf(s_filename, MAXPATHLEN, "/tmp/hphp_takeover_XXXXXX");
int tmpfd = mkstemp(s_filename);
close(tmpfd);
s_func.reset(new AsyncFunc<TestServer>(this, &TestServer::RunServer));
s_func->start();
// Wait for the server to actually start
HttpClient http;
StringBuffer response;
vector<String> responseHeaders;
string url = "http://127.0.0.1:" + lexical_cast<string>(s_server_port) +
"/status.php";
HeaderMap headers;
for (int i = 0; i < 10; i++) {
int code = http.get(url.c_str(), response, &headers, &responseHeaders);
if (code > 0) {
break;
}
sleep(1);
}
// will start a second server, which should takeover
VSR("<?php print 'Hello, World!';",
"Hello, World!");
unlink(s_filename);
s_filename[0] = 0;
return true;
}
示例5: testGetHeader
void testGetHeader(Url&url) {
HttpClient client;
string header;
client.requestHeader(url, header);
cout << header << endl;
}
示例6: _checkUrlText
/**
* Check a GET to a url returns a certain code and data.
*/
static void _checkUrlText(
TestRunner& tr, Url* url, int code, const char* expected, int length)
{
// create client
HttpClient client;
// connect
assertNoException(client.connect(url));
if(tr.getVerbosityLevel() > 1)
{
printf("Connected to: %s\n", url->toString().c_str());
InternetAddress address(url->getHost().c_str(), url->getPort());
printf("%s\n", address.toString().c_str());
}
// do get
HttpResponse* response = client.get(url);
assert(response != NULL);
if(tr.getVerbosityLevel() > 1)
{
printf("Response header:\n%s\n",
response->getHeader()->toString().c_str());
}
if(response->getHeader()->getStatusCode() != code)
{
printf("Expecting response status code: %d, got %d\n",
response->getHeader()->getStatusCode(), code);
}
assert(response->getHeader()->getStatusCode() == code);
// receive content
HttpTrailer trailer;
ByteBuffer b;
ByteArrayOutputStream baos(&b);
assertNoException(client.receiveContent(&baos, &trailer));
// put data in strings for strcmp since it may not be NULL terminated
string strexpected;
strexpected.assign(expected, length);
string strdata;
strdata.assign(b.data(), b.length());
if(tr.getVerbosityLevel() > 1)
{
printf("Response content (%d bytes):\n%s\n", b.length(), strdata.c_str());
printf("Response trailers:\n%s\n", trailer.toString().c_str());
}
// check content
assertStrCmp(strdata.c_str(), strexpected.c_str());
assert(b.length() == length);
client.disconnect();
assertNoExceptionSet();
}
示例7: stats
BSONObj stats() {
if ( _http ) {
HttpClient c;
HttpClient::Result r;
string url;
{
stringstream ss;
ss << "http://" << _host;
if ( _host.find( ":" ) == string::npos )
ss << ":28017";
ss << "/_status";
url = ss.str();
}
if ( c.get( url , &r ) != 200 ) {
cout << "error (http): " << r.getEntireResponse() << endl;
return BSONObj();
}
BSONObj x = fromjson( r.getBody() );
BSONElement e = x["serverStatus"];
if ( e.type() != Object ) {
cout << "BROKEN: " << x << endl;
return BSONObj();
}
return e.embeddedObjectUserCheck();
}
BSONObj out;
if ( ! conn().simpleCommand( _db , &out , "serverStatus" ) ) {
cout << "error: " << out << endl;
return BSONObj();
}
return out.getOwned();
}
示例8: run
virtual void run(void *)
{
while(1)
{
HttpClient * client;
if ( cookies.empty())
client = new HttpClient();
else
client = new HttpClient(cookies);
std::list<std::string> headers;
headers.push_back("Referer: http://d.web2.qq.com/proxy.html");
//std::vector<curlpp::OptionBase*> settings;
//settings.push_back(new curlpp::options::HttpHeader(headers));
//client->setOptions(settings);
client->setHttpHeaders(headers);
std::string result = client->requestServer("http://d.web2.qq.com/channel/poll2",body);
std::cout<<result<<std::endl;
Json::Reader jsonReader;
Json::Value root;
jsonReader.parse(result, root, false);
int ret= root["retcode"].asInt();
if ( ret == 103)
{
debug_info("lost connection.");
sleep(5);
}
delete client;
}
}
示例9: connect
YETI_Result HttpTcpConnector::connect(const HttpUrl & url,
HttpClient & client,
const HttpProxyAddress * proxy,
bool reuse, HttpClient::Connection *& connection)
{
connection = NULL;
const char * server_hostname;
YETI_UInt16 server_port;
if (proxy) {
server_hostname = (const char *)proxy->get_hostname();
server_port = proxy->get_port();
} else {
server_hostname = (const char *)url.get_host();
server_port = url.get_port();
}
IpAddress address;
YETI_CHECK_FINE(address.resolve_name(server_hostname, client.get_config().m_name_resolver_timeout_));
YETI_LOG_FINE_2("TCP connector will connect to %s : %d", server_hostname, server_port);
TcpClientSocket * tcp_socket = new TcpClientSocket();
SocketReference socket(tcp_socket, true);
tcp_socket->set_read_timeout(client.get_config().m_io_timeout_);
tcp_socket->set_write_timeout(client.get_config().m_io_timeout_);
SocketAddress socket_address(address, server_port);
YETI_CHECK_FINE(tcp_socket->connect(socket_address, client.get_config().m_connection_timeout_));
HttpSimpleConnection * _connection = new HttpSimpleConnection();
_connection->m_socket_ = socket;
connection = _connection;
tcp_socket->get_input_stream(_connection->m_inputstream_);
tcp_socket->get_output_stream(_connection->m_outputstream_);
return YETI_SUCCESS;
}
示例10: TEST
TEST(HttpClient_ParseUrl, TestParseUrl2) {
HttpClient client;
EXPECT_EQ(client._parse_url("www.baidu.com"), -1);
EXPECT_EQ(client._parse_url("httpssss://www.baidu.com"), -1);
EXPECT_EQ(client._parse_url("https://www.google.com:12332:"), -1);
EXPECT_EQ(client._parse_url("http:/www.baidu.com"), -1);
}
示例11: message_complete_cb
int HttpClient::message_complete_cb(http_parser* parser)
{
HttpClient* client = static_cast<HttpClient*>(parser->data);
client->handler_.OnHttpResponse(client, client->resp_body_.c_str());
// 主动关闭, TODO 后期可优化keep-alive,制作一个HttpClient池
client->Close();
return 0;
}
示例12: assert
bool HttpProtocol::ProxyRequest(Transport *transport, bool force,
const std::string &url,
int &code, std::string &error,
StringBuffer &response,
HeaderMap *extraHeaders /* = NULL */) {
assert(transport);
if (transport->headersSent()) {
raise_warning("Cannot proxy request - headers already sent");
return false;
}
HeaderMap requestHeaders;
transport->getHeaders(requestHeaders);
if (extraHeaders) {
for (HeaderMap::const_iterator iter = extraHeaders->begin();
iter != extraHeaders->end(); ++iter) {
std::vector<std::string> &values = requestHeaders[iter->first];
values.insert(values.end(), iter->second.begin(), iter->second.end());
}
}
int size = 0;
const char *data = nullptr;
if (transport->getMethod() == Transport::Method::POST) {
data = (const char *)transport->getPostData(size);
}
std::vector<String> responseHeaders;
HttpClient http;
code = http.request(transport->getMethodName(),
url.c_str(), data, size, response, &requestHeaders,
&responseHeaders);
if (code == 0) {
if (!force) return false; // so we can retry
Logger::Error("Unable to proxy %s: %s", url.c_str(),
http.getLastError().c_str());
error = http.getLastError();
return true;
}
for (unsigned int i = 0; i < responseHeaders.size(); i++) {
String &header = responseHeaders[i];
if (header.find(":") != String::npos &&
header.find("Content-Length: ") != 0 &&
header.find("Client-Transfer-Encoding: ") != 0 &&
header.find("Transfer-Encoding: ") != 0 &&
header.find("Connection: ") != 0) {
transport->addHeader(header.data());
}
}
const char* respData = response.data();
if (!respData) {
respData = "";
}
Logger::Verbose("Response code was %d when proxying %s", code, url.c_str());
return true;
}
示例13: cmd_getweather
static void cmd_getweather(BaseSequentialStream *chp, int argc, char *argv[])
{
(void)argv;
if (argc > 0) return;
HttpClient test;
HttpJsonData jsondatahandler;
test.connect((const char *) "http://api.openweathermap.org/data/2.5/weather?q=Singapore,sg", HTTP_GET, &jsondatahandler);
}
示例14: Refresh
void TwitterFeed::Refresh()
{
HttpClient http;
if (client.ResourceRequiresAuthentication(resource)) {
client.SetAuth(http);
}
while (true) {
thread->TestDestroy();
wxXmlDocument doc = http.GetXml(wxURL(Twitter::StatusesBaseUrl + resource + _T(".xml")));
wxXmlNode *root = doc.GetRoot();
if (root != NULL) {
wxXmlNode *node = root->GetChildren();
// create a list of the status nodes
vector<wxXmlNode*> nodes;
while (node) {
if (node->GetName() == _T("status")) {
nodes.push_back(node);
}
node = node->GetNext();
}
// read nodes backwards
vector<wxXmlNode*>::reverse_iterator it;
for (it = nodes.rbegin(); it != nodes.rend(); ++it) {
thread->TestDestroy();
try {
TwitterStatus status(client, **it);
if (AddStatus(status)) {
// notify listeners if the status was added
client.NotifyListeners(resource);
}
}
catch (...) {
// parsing the node might have failed.
}
}
// notify listeners if the status was added
// NotifyListeners(resource);
}
// What a perfect opportunity to save this resource
Save();
// Delay but make sure we can leave the thread easily
for (unsigned int i = 0; i < delay; i++) {
thread->TestDestroy();
wxSleep(1);
}
}
}
示例15: put_message
static void put_message(const char *msg) {
struct mg_request_info ri;
std::string nm = HEADERS[CREATE_HDR];
char *resp;
int cnt = 0, i;
int n = sscanf(msg + 1, "%d %d", &cnt, &i);
if (cnt <= 0) {
resp = _wc.send(&ri, "POST", nm.c_str(), "*/*", msg, NULL);
if (ri.status_code == 201)
decode_headers(&ri);
} else {
while (cnt--) {
char m[32];
sprintf(m, "MSG %d", i++);
printf("%s\n", m);
resp = _wc.send(&ri, "POST", nm.c_str(), "*/*", m, NULL);
if (ri.status_code == 201)
decode_headers(&ri);
else
printf("POST status: %d\n", ri.status_code);
}
}
}