void http_request_async(const http_request_t * request, void (*callback)(http_response_t*)) { auto request2 = HttpRequest2(request); auto thread = std::thread([](const HttpRequest2 &req, void(*callback2)(http_response_t*)) -> void { http_response_t * response = http_request(req); callback2(response); }, std::move(request2), callback); thread.detach(); }
int sohuGetInternetIp(IpQueryCxt* ctx) { std::vector<char> content_buff; if(http_request("http://pv.sohu.com/cityjson?ie=utf-8",content_buff,&(ctx->sock)) < 0 ) { LOG(msgINFO,"sinaLocation\n"); return -1; } return sohu_parsedata(content_buff,ctx); }
FListWebRequestData* flist_web_request(const gchar* url, GHashTable* args, gboolean post, FListWebCallback cb, gpointer data) { gchar *http = http_request(url, FALSE, post, USER_AGENT, args, NULL); FListWebRequestData *ret = g_new0(FListWebRequestData, 1); PurpleUtilFetchUrlData *url_data = purple_util_fetch_url_request(url, FALSE, USER_AGENT, FALSE, http, FALSE, flist_web_request_cb, ret); ret->url_data = url_data; ret->cb = cb; ret->user_data = data; ret->timer = purple_timeout_add_seconds(FLIST_WEB_REQUEST_TIMEOUT, (GSourceFunc) flist_web_request_timeout, ret); g_hash_table_insert(requests, ret, ret); return ret; }
//get local weather, function two: void get_local_weather2() { char *pp = (char *)malloc(MAX); memset(pp, 0, MAX); char *city_id_json = (char *)malloc(MAX); memset(city_id_json, 0, MAX); char *city_weather_info = (char *)malloc(MAX); memset(city_weather_info, 0, MAX); pp = http_request("iplookup.php?format=json", "/iplookup/", "int.dpool.sina.com.cn", 80); //printf("11111111111111%s\n",pp); char *t = extract_weather_json(pp, 14); //printf("%s\n", t); char *city_name = parse_json_local_cityname(t); //printf("*********%s********\n", city_name); city_id_json = http_request(city_name, "/search?cityname=", "61.4.185.213", 80); //printf("22222222222222%s\n",city_id_json); char *cityid; cityid = extract_city_id(city_id_json); char *ss = strcat(cityid, ".html"); city_weather_info = http_request(ss, "/data/cityinfo/", "61.4.185.201", 80); //printf("333333333333333city_weather_info\n%s\n", city_weather_info); char *city_weather_json = extract_weather_json(city_weather_info, 8); //printf("city_weather_json\n%s\n",city_weather_json); char *weather = parse_json(city_weather_json); printf("%s\n", weather); char *city_name1 = city_name; //printf("%s\n", city_name1); char *file_name = strcat(city_name1, ".cache"); free(pp); free(city_id_json); free(city_weather_info); }
static void http_poll_timer_cb(struct ev_loop *loop, struct ev_timer *w, int revents) { struct http_ctx *ctx = w->data; if (!ctx->in_flight) { ctx->in_flight = 1; if (buffer_queue_len(ctx->egress) > 0) { ctx->data.content_len = buffer_queue_remove_all(ctx->egress, &ctx->data.content); http_request(ctx->uri, http_request_post, http_poll_cb, ctx, &ctx->data, &ctx->opts); ctx->data.content_len = 0; ctx->data.content = NULL; } else { http_request(ctx->uri, http_request_get, http_poll_cb, ctx, &ctx->data, &ctx->opts); } } if (ctx->running) { ev_timer_again(c2_transport_loop(ctx->t), &ctx->poll_timer); } }
char * zurl(const char * url, char * opt){ const char * host = get_host(url); const char * uri = get_uri(url); unsigned int m,n; m = n = 0; struct field * data = get_data(uri,&m); struct field * params = get_params(uri,&n); char * buffer = http_request("GET", host, uri, HTTP_EDITION, params, m, data, n,1); free_kv(data,m); free_kv(params,n); return buffer; }
int gs_start_app(PSERVER_DATA server, STREAM_CONFIGURATION *config, int appId, bool sops, bool localaudio) { int ret = GS_OK; uuid_t uuid; char* result = NULL; char uuid_str[37]; if (config->height >= 2160 && !server->supports4K) return GS_NOT_SUPPORTED_4K; RAND_bytes(config->remoteInputAesKey, 16); memset(config->remoteInputAesIv, 0, 16); srand(time(NULL)); char url[4096]; u_int32_t rikeyid = 0; char rikey_hex[33]; bytes_to_hex(config->remoteInputAesKey, rikey_hex, 16); PHTTP_DATA data = http_create_data(); if (data == NULL) return GS_OUT_OF_MEMORY; uuid_generate_random(uuid); uuid_unparse(uuid, uuid_str); if (server->currentGame == 0) { int channelCounnt = config->audioConfiguration == AUDIO_CONFIGURATION_STEREO ? CHANNEL_COUNT_STEREO : CHANNEL_COUNT_51_SURROUND; int mask = config->audioConfiguration == AUDIO_CONFIGURATION_STEREO ? CHANNEL_MASK_STEREO : CHANNEL_MASK_51_SURROUND; sprintf(url, "https://%s:47984/launch?uniqueid=%s&uuid=%s&appid=%d&mode=%dx%dx%d&additionalStates=1&sops=%d&rikey=%s&rikeyid=%d&localAudioPlayMode=%d&surroundAudioInfo=%d", server->address, unique_id, uuid_str, appId, config->width, config->height, config->fps, sops, rikey_hex, rikeyid, localaudio, (mask << 16) + channelCounnt); } else sprintf(url, "https://%s:47984/resume?uniqueid=%s&uuid=%s&rikey=%s&rikeyid=%d", server->address, unique_id, uuid_str, rikey_hex, rikeyid); if ((ret = http_request(url, data)) == GS_OK) server->currentGame = appId; else goto cleanup; if ((ret = xml_search(data->memory, data->size, "gamesession", &result)) != GS_OK) goto cleanup; if (!strcmp(result, "0")) { ret = GS_FAILED; goto cleanup; } cleanup: if (result != NULL) free(result); http_free_data(data); return ret; }
void* http_thread::run() { char domain[256]; unsigned short port; if (acl::http_utils::get_addr(url_.c_str(), domain, sizeof(domain), &port) == false) { logger_error("invalid url: %s", url_.c_str()); return NULL; } char host[256], *phost; if (port == 80) phost = domain; else { snprintf(host, sizeof(host), "%s:%d", domain, port); phost = host; } struct timeval begin0; gettimeofday(&begin0, NULL); struct timeval begin, end; // 连接 HTTP 服务器并计算耗时 gettimeofday(&begin, NULL); acl::socket_stream* conn = connect_server(); gettimeofday(&end, NULL); spent_connect_ = util::stamp_sub(&end, &begin); if (conn == NULL) return NULL; gettimeofday(&begin, NULL); if (http_request(conn, phost) == false) logger_error("http request failed!"); gettimeofday(&end, NULL); struct timeval finish; gettimeofday(&finish, NULL); spent_http_ = util::stamp_sub(&end, &begin); spent_total_ = spent_dns_ + util::stamp_sub(&finish, &begin0); delete conn; return NULL; }
int satipc_timeout(sockets *s) { adapter *ad = get_adapter(s->sid); LOG( "satipc: Sent keep-alive to the satip server %s:%d, adapter %d, socket_id %d, handle %d, timeout %d", ad?ad->sip:NULL, ad ? ad->sport : 0, s->sid, s->id, s->sock, s->close_sec); if (!ad) return 1; http_request(ad, NULL, "OPTIONS"); s->rtime = getTick(); return 0; }
const struct etcd_data *etcd_get(const char *key) { char *url; const struct etcd_data *retdata; if (!is_valid_key(key)) { return NULL; } url = etcd_url(key, NULL); retdata = http_request(url, ETCD_GET, NULL); free(url); return retdata; }
void update_nonce(void) { struct cJSON *result, *data = cJSON_CreateObject(); unsigned char i; char rand[RAND_SIZE]; cJSON_AddItemToObjectCS(data, "operation", cJSON_CreateString("get_nonce")); add_random_response(data, rand); cJSON_AddItemToObjectCS(data, "version", cJSON_CreateNumber(2)); i = http_request(data, &result, rand); if (i == RESPONSE_GOOD) cJSON_Delete(result); }
void http_request_async(const http_request_t *request, void (*callback)(http_response_t*)) { struct TempThreadArgs { http_request_t request; void (*callback)(http_response_t*); }; TempThreadArgs *args = (TempThreadArgs*)malloc(sizeof(TempThreadArgs)); args->request.url = _strdup(request->url); args->request.method = request->method; if (request->type == HTTP_DATA_JSON) { args->request.root = json_deep_copy(request->root); } else { char* bodyCopy = (char*) malloc(request->size); memcpy(bodyCopy, request->body, request->size); args->request.body = bodyCopy; } args->request.type = request->type; args->request.size = request->size; args->request.tag = request->tag; args->callback = callback; SDL_Thread *thread = SDL_CreateThread([](void *ptr) -> sint32 { TempThreadArgs *args2 = (TempThreadArgs*)ptr; http_response_t *response = http_request(&args2->request); args2->callback(response); free((char*)args2->request.url); if (args2->request.type == HTTP_DATA_JSON) { json_decref((json_t*) args2->request.root); } else { free(args2->request.body); } free(args2); return 0; }, NULL, args); if (thread == NULL) { log_error("Unable to create thread!"); callback(NULL); } else { SDL_DetachThread(thread); } }
bool DownloadUpdate() { bool result = false; if(updateURL[0] == 0 || appPath[0] == 0 || !ChangeInterface(appPath, NOTSILENT)) { ErrorPrompt("Update failed!"); updateFound = false; // updating is finished (successful or not!) return false; } // stop checking if devices were removed/inserted // since we're saving a file HaltDeviceThread(); int device; FindDevice(appPath, &device); char updateFile[50]; sprintf(updateFile, "%s%s Update.zip", pathPrefix[device], APPNAME); FILE * hfile = fopen (updateFile, "wb"); if (hfile) { if(http_request(updateURL, hfile, NULL, (1024*1024*10), NOTSILENT) > 0) { fclose (hfile); result = unzipArchive(updateFile, (char *)pathPrefix[device]); } else { fclose (hfile); } remove(updateFile); // delete update file } // go back to checking if devices were inserted/removed ResumeDeviceThread(); if(result) InfoPrompt("Update successful!"); else ErrorPrompt("Update failed!"); updateFound = false; // updating is finished (successful or not!) return result; }
void http(int fd) { int YARDSTIICK = 4000; int eof = 0; while (! eof) { if (++total_requests % YARDSTIICK == 0) { double cur_time = time(0); printf("rps: %d\n", (int) (YARDSTIICK/(cur_time - prev_time))); prev_time = cur_time; } eof = http_request(fd); } close(fd); }
int gs_quit_app(PSERVER_DATA server) { char url[4096]; uuid_t uuid; char uuid_str[37]; PHTTP_DATA data = http_create_data(); if (data == NULL) return GS_OUT_OF_MEMORY; uuid_generate_random(uuid); uuid_unparse(uuid, uuid_str); sprintf(url, "https://%s:47984/cancel?uniqueid=%s&uuid=%s", server->address, unique_id, uuid_str); int ret = http_request(url, data); http_free_data(data); return ret; }
bool GUIMultiplayerMenu::fetchServers() { char* u = const_cast<char*>("/list"); std::string data = http_request(NULL,u); std::string path = getPath("","servers.txt",false); std::ofstream f; f.open(path.c_str()); if (!f.is_open()) return false; f << data; f.close(); return loadServers(); }
// get local city ID, example:成都的ID char *extract_local_city_id() { char *temp = http_request("", "/g/", "61.4.185.48", 81); //printf("%s\n", temp); char *result = extract_weather_json(temp, 9); //printf("%s\n", result); char *p1 = "id="; char *p2 = strstr(result,p1); // printf("%s\n",p2); char *p4= "="; char *p3 = strstr(p2,p4); //printf("%s\n",p3+1); strncpy(local_city_id, p3+1, 9); // printf("%s\n", local_city_id); return local_city_id; }
/*get local weather, 获取计算机所在地的天气信息, *但是存在小bug,获取天气信息速度较慢且并不能保证每次都能成功连接并获取信息; *get_local_weather2()该函数可以准确迅速获取当地信息. function one: */ void get_local_weather() { char *file_name = "chengdu.cahe"; //int exist = access(file_name, 0); printf("local report:\n"); char *local_city_ID = extract_local_city_id(); //printf("%s\n", local_city_ID); char *ss = strcat(local_city_ID, ".html"); char *city_weather_info = http_request(ss, "/data/cityinfo/", "61.4.185.201", 80); char *city_weather_json = extract_weather_json(city_weather_info, 8); char *weather = parse_json(city_weather_json); printf("%s\n", weather); ssize_t weather_len = strlen(weather); write_cache(weather, file_name, weather_len); }
int main(int argc, char *argv[]) { if(argc < 2) { printf("Usage ./main MD1AC44200003128\n"); return EXIT_FAILURE; } int prev_value = 100; int recent_value = 1; FILE* stream; char request[1024], buf[1024], json[1024]; stream = fopen("config.ini", "r"); fread(buf, sizeof(char), sizeof(buf), stream); fclose(stream); printf("Bulb: %s\n", argv[1]); while(1) { sprintf(request, "https://io.adafruit.com/api/feeds/qstation?x-aio-key=%s", buf); recent_value = http_request(request); if(prev_value != 100 && recent_value != prev_value) { if(recent_value == 2) { printf("Turn bulb off.\n"); sprintf(json, "{\"iswitch\":\"0\",\"r\":\"255\",\"g\":\"255\",\"b\":\"255\",\"bright\":\"20\",\"cmd\":\"light_ctrl\",\"effect\":\"9\",\"sn_list\":[{\"sn\":\"%s\"}]}", argv[1]); udp_send(json); } else if(recent_value == 3) { printf("Turn bulb on.\n"); sprintf(json, "{\"iswitch\":\"1\",\"r\":\"255\",\"g\":\"255\",\"b\":\"255\",\"bright\":\"20\",\"cmd\":\"light_ctrl\",\"effect\":\"9\",\"sn_list\":[{\"sn\":\"%s\"}]}", argv[1]); udp_send(json); } else printf("ERROR: Unknown value.\n"); } prev_value = recent_value; sleep(10); } return EXIT_SUCCESS; }
void* https_client::run() { struct timeval begin; gettimeofday(&begin, NULL); int n = http_request(count_); if (n != count_) printf(">>>>SOME TASK NOT COMPLETE!<<<<<\r\n"); struct timeval end; gettimeofday(&end, NULL); double spent = util::stamp_sub(&end, &begin); printf("total: %d, spent: %.2f, speed: %.2f\r\n", count_, spent, (n * 1000) / (spent > 1 ? spent : 1)); return NULL; }
void get_news() { char *re = (char *)malloc(MAX); memset(re, 0, MAX); char *out = (char *)malloc(MAX); memset(out, 0, MAX); re = http_request("rollnews_ch_out_interface.php","/interface/", "roll.news.sina.com.cn", 80); g2u(re, strlen(re), out, MAX); //printf("%s\n", out); char *new_json = extract_news_json(out, 19); printf("%s\n", new_json); free(re); free(out); }
PurpleUtilFetchUrlData *flist_login_fls_request(PurpleConnection *pc, const gchar *user_agent, const gchar *username, const gchar *password, PurpleUtilFetchUrlCallback callback) { gchar *url = "http://www.f-list.net/action/script_login.php"; PurpleUtilFetchUrlData *ret; GHashTable *post = g_hash_table_new_full(g_str_hash, g_str_equal, NULL, NULL); gchar *request; g_hash_table_insert(post, (gpointer) "username", (gpointer) username); g_hash_table_insert(post, (gpointer) "password", (gpointer) password); request = http_request(url, FALSE, TRUE, user_agent, post, NULL); ret = purple_util_fetch_url_request(url, FALSE, user_agent, FALSE, request, TRUE, callback, pc); g_free(request); g_hash_table_destroy(post); return ret; }
void prot_user_request_token_reply( struct qqclient* qq, qqpacket* p ) { bytebuffer *buf = p->buf; uchar cmd = get_byte( buf ); get_word( buf ); //0006 uchar verify = get_byte( buf ); if( verify ){ char *url, *data, *session; int datalen = KB(4); DBG (("need verifying...")); if( buf->pos == buf->len ) { puts("Verifying code is incorrect!"); return; //verify code wrong. } int len, ret; len = get_word( buf ); if( len >= 128 ){ DBG (("url is too long.")); return; } NEW( char*, data, datalen ); NEW( char*, url, 128 ); NEW( char*, session, 128 ); get_data( buf, (uchar*)url, len ); ret = http_request( &qq->http_sock, url, session, data, &datalen ); if( ret == 0 ){ char path[PATH_LEN]; sprintf( path, "%s/%u.jpg", qq->verify_dir, qq->number ); FILE *fp; fp = fopen( path, "wb" ); DBG (("got png at %s", path )); if( fp ){ fwrite( data, datalen, 1, fp ); fclose( fp ); } strncpy( qq->data.qqsession, session, 127 ); qqclient_set_process( qq, P_VERIFYING ); puts("You need to input the verifying code."); }else{ DBG (("http_request failed. ret=%d", ret )); } DEL( data ); DEL( url ); DEL( session ); }else{
bool http_download_park(const char *url, char tmpPath[L_tmpnam + 10]) { // Download park to buffer in memory http_request_t request; request.url = url; request.method = "GET"; request.type = HTTP_DATA_NONE; http_response_t *response = http_request(&request); if (response == NULL || response->status_code != 200) { Console::Error::WriteLine("Failed to download '%s'", request.url); if (response != NULL) { http_request_dispose(response); } return false; } // Generate temporary filename that includes the original extension if (tmpnam(tmpPath) == NULL) { Console::Error::WriteLine("Failed to generate temporary filename for downloaded park '%s'", request.url); http_request_dispose(response); return false; } size_t remainingBytes = L_tmpnam + 10 - strlen(tmpPath); const char *ext = http_get_extension_from_url(request.url, ".sv6"); strncat(tmpPath, ext, remainingBytes); // Store park in temporary file and load it (discard ending NUL in response body) FILE* tmpFile = fopen(tmpPath, "wb"); if (tmpFile == NULL) { Console::Error::WriteLine("Failed to write downloaded park '%s' to temporary file", request.url); http_request_dispose(response); return false; } fwrite(response->body, 1, response->size - 1, tmpFile); fclose(tmpFile); http_request_dispose(response); return true; }
etcd_response etcd_test_and_set(const char *key, const char *value, const char *oldValue, unsigned ttl) { char *url, *data, *tmpdata; const struct etcd_data *retdata; etcd_response response; int ret; if (!is_valid_key(key) || !is_valid_value(value)) { return ETCD_FAILURE; } if (!is_valid_value(oldValue)) { /* If the old value is NULL, then this should act like etcd_set() */ if (oldValue == NULL) { return etcd_set(key, value, ttl); } return ETCD_FAILURE; } url = etcd_url(key, NULL); ret = asprintf(&data, "value=%s&prevValue=%s", value, oldValue); assert(ret >= 0); if (ttl > 0) { ret = asprintf(&tmpdata, "%s&ttl=%u", data, ttl); assert(ret >= 0); free(data); data = tmpdata; } retdata = http_request(url, ETCD_SET, data); assert(retdata != NULL); response = retdata->response; if (response == ETCD_FAILURE) { debug(retdata->errmsg); } free(url); free(data); free((struct etcd_data *)retdata); return response; }
/* http over */ int http_over(CONN *conn, int respcode) { int id = 0, n = 0; if(conn) { conn->over_cstate(conn); id = conn->c_id; if(ncompleted < ntasks) ++ncompleted; else return conn->over(conn); n = ncompleted; if(n > 0 && n <= ntasks && (n%1000) == 0) { if(is_quiet) { REALLOG(logger, "completed %d current:%d", n, ncurrent); } else fprintf(stdout, "completed %d current:%d\n", n, ncurrent); } if(ncompleted < ntasks) { if(conn->d_state == 0 && is_keepalive && respcode != 0) return http_request(conn); else { conn->close(conn); if(respcode != 0 && respcode != 200)nerrors++; if(http_newconn(id, server_ip, server_port, server_is_ssl) == NULL) { if(ncurrent > 0)--ncurrent; } } } else { conn->close(conn); if(n == ntasks) return http_show_state(n); } } return -1; }
int sinaLocation(char* ip,IpQueryCxt* ctx) { std::string url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip="; //std::string url = "http://m3.file.xiami.com/h/2WzPHIYaumlmgKSTS4w3SiUc5uHcHzOOxI1pkLIlsR0mIYsBZZz9kpqTRg9X2SeVoVAZF7ud3FRPGOhdLNCjpvWVQgPa"; if(ip) url.append(ip); std::vector<char> content_buff; if(http_request(url.c_str(),content_buff,&(ctx->sock)) < 0 ) { LOG(msgERROR,"sinaLocation\n"); return -1; } return sina_parsedata(content_buff,ctx->replay); }
http_download::http_download(const char* url, const char* addr /* = NULL */) { if (addr) ACL_SAFE_STRNCPY(addr_, addr, sizeof(addr)); else if (http_utils::get_addr(url, addr_, sizeof(addr_)) == false) { logger_error("url(%s) invalid", url); addr_[0] = 0; url_ = NULL; req_ = NULL; return; } url_ = acl_mystrdup(url); req_ = NEW http_request(addr_); // HTTP 请求对象 req_->request_header().set_url(url_) .set_content_type("text/html") .set_host(addr_); }
/* initialize the interface to the GA engine by contacting the engine at url and getting a set of weights in the form of an XML file. Parse out the weights and the ID and put them into static global variables */ void GAinit(const char *url) { char url_cmd[MAX_URL_LEN]; HTTP_Response hResponse; if (debug && myrank == 0) fprintf(stderr, "GAinit: url = %s\n", url); /* zero out the weight array and nweights */ { unsigned i; for (i=0; i<MAX_WEIGHTS;i++) { memset(weights[i].weight,0,WEIGHT_LEN); weights[i].value = 0.0; } nweights = 0; } /* copy url into GA_URL for future use */ strcpy(GA_URL,url); if (GA_URL[strlen(GA_URL) - 1] == '/' || GA_URL[strlen(GA_URL) - 1] == '\\' ) GA_URL[strlen(GA_URL) - 1] = '\0'; /* construct the get baby cmd url */ sprintf(url_cmd, "%s/%s?%s", GA_URL, ROOT_CMD, GET_BABY); /* actually get the XML document from the server */ hResponse = http_request(url_cmd, NULL, kHMethodGet, HFLAG_NONE); /* if we got the XML document so call the parser to fill in weights array */ if (hResponse.lSize > 0) XMLParseString(hResponse.pData, hResponse.lSize); else /* otherwise there was an error */ { sprintf(estring,"Error GAInit: Error retrieving baby\n"); errorExit(estring); } /* we have to free up the pData from the response when done */ if (hResponse.pData) free(hResponse.pData); }
bool DownloadUpdate() { bool result = false; if(strlen(updateURL) > 0) { // stop checking if devices were removed/inserted // since we're saving a file LWP_SuspendThread (devicethread); FILE * hfile; char updateFile[50]; sprintf(updateFile, "sd:/%s Update.zip", APPNAME); hfile = fopen (updateFile, "wb"); if (hfile > 0) { int retval; retval = http_request(updateURL, hfile, NULL, (1024*1024*5)); fclose (hfile); } bool unzipResult = unzipArchive(updateFile, (char *)"sd:/"); remove(updateFile); // delete update file if(unzipResult) { result = true; WaitPrompt("Update successful!"); } else { result = false; WaitPrompt("Update failed!"); } updateFound = false; // updating is finished (successful or not!) // go back to checking if devices were inserted/removed LWP_ResumeThread (devicethread); } return result; }