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); }
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); } } }
//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; }
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; } }
int main() { Log::setLevel(Log::info); ::signal(SIGINT, signalStop); setlimit(100000); errno = 0; client.start(); for(int i = 0; i < CliNum ; i++) { stringstream ss; int port = Port + (i % PortNum); ss << "127.0.0.1" << ":" << port << "/subscribe?channel=" ; ss << (i % ChanNum) << "&sname=user" << i << "&seqid=0&callback=callback"; client.request(ss.str(), get, error, NULL); usleep(5*1000); } client.wait(); return 0; }
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; }
void sendData() { // We need to wait if a previous request processing is still processing if (thisFrame.isProcessing()) return; // Call the sensor and get the response thisFrame.downloadString(sensorAddress, onDataSent); }
void testGetHeader(Url&url) { HttpClient client; string header; client.requestHeader(url, header); cout << header << endl; }
/** * 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(); }
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(); }
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; } }
int main() { Log::setLevel(Log::debug); ::signal(SIGINT, signalStop); setlimit(100000); errno = 0; client.start(); /// bbs.sjtu.edu.cn /// client.request("202.120.58.161", get, error, NULL); /// yulongti.info/?p=2761 /// client.request("128.199.204.82/?p=2761", get, error, NULL); for(int i = 0; i < CLINUM; i++) { stringstream ss; int port = Port + (i % PortNum); ss << "127.0.0.1" << ":" << port << "/sub"; client.request(ss.str(), get, error, NULL); usleep(5 * 1000); } client.wait(); return 0; }
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; }
void sendData() { char hum[16]; char temp[256]; #ifdef KEIL_SERVER_EXIST sensorValue++; // two or one server #else sensorValue+=2; #endif if (thingSpeak.isProcessing()) { // thingSpeak.reset(); LastErr[sensorValue&1]=6; Serial.println("LastErr=6"); return; // We need to wait while request processing was completed } float h = 0; //dht.readHumidity(); float t = Read_DS18(); // check if returns are valid, if they are NaN (not a number) then something went wrong! if (isnan(t) || (t == 5000)) { Serial.println("Failed to read from DS1820 - not send"); } else { Serial.println(" "); if (sensorValue & 1) Serial.println("THINGSPEAK"); else Serial.println("KEIL"); Serial.print("Temperature: "); Serial.print(t); Serial.println(" *C"); t=t*100; t=t/10; #ifdef BMP_180 Read_BMP180 (); if (sensorValue & 1) os_sprintf(temp, "http://%s/update?key=%s&field1=%d.%01d&field7=%d.%01d&field8=%d.%01d&status=dev_ip:192.168.0.180",THINGSPEAK_SERVER,THINGSPEAK_API_KEY,(int)(t/10),(int)t%10,(int)(cctemp/10),(int)cctemp%10,(int)(ccpres/10),(int)ccpres%10); else os_sprintf(temp, "http://%s/u?k&f1=%d.%01d&f7=%d.%01d&f8=%d.%01d&k",KEIL_SERVER,(int)(t/10),(int)t%10,(int)(cctemp/10),(int)cctemp%10,(int)(ccpres/10),(int)ccpres%10); #else if (sensorValue & 1) os_sprintf(temp, "http://%s/update?key=%s&field5=%d.%01d&status=dev_ip:192.168.0.186",THINGSPEAK_SERVER,THINGSPEAK_API_KEY,(int)(t/10),(int)t%10); else os_sprintf(temp, "http://%s/u?k&f5=%d.%01d&k",KEIL_SERVER,(int)(t/10),(int)t%10); #endif thingSpeak.downloadString(String(temp),onDataSent); } }
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); }
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; }
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; }
void sendData() { char hum[16]; char temp[16]; char temp2[256]; #ifdef KEIL_SERVER_EXIST sensorValue++; // two or one server #else sensorValue+=2; #endif if (thingSpeak.isProcessing()) { // thingSpeak.reset(); LastErr[sensorValue&1]=6; Serial.println("LastErr=6"); return; // We need to wait while request processing was completed } // Read our sensor value :) float h = dht.readHumidity(); float t = dht.readTemperature(); // check if returns are valid, if they are NaN (not a number) then something went wrong! if (isnan(t) || isnan(h)) { Serial.println("Failed to read from DHT - not send"); } else { Serial.println(" "); if (sensorValue & 1) Serial.println("THINGSPEAK"); else Serial.println("KEIL"); Serial.print("Humidity: "); Serial.print(h); Serial.print(" %\t"); Serial.print("Temperature: "); Serial.print(t); Serial.println(" *C"); t=t*10; h=h*10; os_sprintf(temp, "%d.%01d",(int)(t/10),(int)t%10); os_sprintf(hum, "%d.%01d",(int)(h/10),(int)h%10 ); if (sensorValue & 1) os_sprintf(temp2, "http://%s/update?key=%s&field6=%s&field2=%s&status=dev_ip:192.168.0.188",THINGSPEAK_SERVER,THINGSPEAK_API_KEY,temp,hum); else os_sprintf(temp2, "http://%s/u?k&f6=%s&f2=%s&s",KEIL_SERVER,temp,hum); thingSpeak.downloadString(String(temp2),onDataSent); } }
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); }
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); } } }
void sendData() { if (ifttt.isProcessing()) return; if((digitalRead(bt_pin)) && (bt_status == 0)) { bt_status = 1; ifttt.downloadString("http://maker.ifttt.com/trigger/"+ String(EVENT) +"/with/key/" + String(MAKER_KEY), onDataSent); } }
TEST(HttpClient_ParseUrl, TestParseUrl3) { HttpClient client; EXPECT_EQ(client._parse_url("https://www.google.com/123"), 0); EXPECT_EQ(client._port, 443); EXPECT_EQ(client._host, "www.google.com"); EXPECT_EQ(client._url, "/123"); EXPECT_EQ(client._proto, "https"); }
static void runHttpClientRedirectLoopTest(TestRunner& tr) { tr.test("Http Client Redirect Loop"); // start a kernel Kernel k; k.getEngine()->start(); // create server Server server; InternetAddress address("0.0.0.0", 19123); // create SSL/generic http connection servicer HttpConnectionServicer hcs; server.addConnectionService(&address, &hcs); // create redirect loop http request servicer RedirectLoopHttpRequestServicer loop("/loop"); hcs.addRequestServicer(&loop, false); if(server.start(&k)) { printf("\nServer started on %s\n", address.toString(false).c_str()); // create client HttpClient client; printf("Connecting and expecting a redirect loop...\n"); // do get Url url("http://localhost:19123/loop"); HttpResponse* response = client.get(&url, NULL, 2); if(response != NULL) { printf("Response=\n%s\n", response->getHeader()->toString().c_str()); } else { printf("Correctly detected an exception:\n"); printf("'%s'\n", Exception::get()->getMessage()); } client.disconnect(); } else if(Exception::get() != NULL) { printf("\nServer start failed with errors=%s\n", Exception::get()->getMessage()); } tr.passIfException(); // stop server and kernel server.stop(); k.getEngine()->stop(); Exception::clear(); }
TEST_F(HttpClientTest, GetWithBadProxy) { HttpClient client; HttpResponse response; HttpClient::ErrorCode error; client.SetProxy("http://-proxy.tencent.com:8080"); EXPECT_FALSE(client.Get(m_server_address + "/hello.txt", &response, &error)); EXPECT_EQ(HttpClient::ERROR_INVALID_PROXY_ADDRESS, error); }
TEST_F(HttpClientTest, GetWithBadURI) { HttpClient client; HttpResponse response; HttpClient::ErrorCode error; std::string bad_uri = "http://-www.qq.com"; EXPECT_FALSE(client.Get(bad_uri, &response, &error)); EXPECT_EQ(HttpClient::ERROR_INVALID_URI_ADDRESS, error); }
AnnounceResults RemoteTracker::announce() { auto announceList = _metainfo.getAnnounceList(); std::string uri = createAnnounceUri(announceList[0][0], _metainfo.getInfoSha1Hash(), 55555, 0, 0, 1234567, TEV_STARTED); HttpClient client; std::string returned = client.downloadFile(uri); return parseAnnounceResult(returned); }
TEST(HttpClient_ParseUrl, TestParseUrl1) { HttpClient client; EXPECT_EQ(client._parse_url("http://www.baidu.com"), 0); EXPECT_EQ(client._port, 80); EXPECT_EQ(client._host, "www.baidu.com"); EXPECT_EQ(client._url, "/"); EXPECT_EQ(client._proto, "http"); }
TEST(HttpClient, SslNoVerification) { HttpClient c; c.SetHttpsVerifyPeers(false); c.SetUrl("https://bitbucket.org/sjodogne/orthanc/raw/Orthanc-0.9.3/Resources/Configuration.json"); Json::Value v; c.Apply(v); ASSERT_TRUE(v.isMember("LuaScripts")); }
char *HttpManager::doHttpPost(const char *url) const { HttpClient* httpClient = new HttpClient(); struct HttpRequestGet* httpRequestPost = (HttpRequestGet*) httpClient->startHttpRequest(url, REQUEST_POST_FLAG, HTTP_CONTENT_TYPE_URL_ENCODED, NULL); char * result = httpRequestPost->response; httpClient->httpRequestFree(httpRequestPost, REQUEST_GET_FLAG); delete httpClient; return result; }
int main() { HttpClient client; _HttpRequest request = std::make_shared<HttpRequest>(); _HttpResponse response = client.execute(request); System::out::println(response); return 0; }