2011-08-23 108 views
2

我已經創建了一個PHP和C#應用程序,可以從他們的gamertag獲取用戶Xbox 360配置文件ID。在C++中獲取頁面內容

我只是想知道我是如何做一個Web請求,並將網頁的內容放入C++中的字符串。

謝謝。

+4

不知道我是否理解你的問題,但它聽起來像你想'curl.h'。 –

回答

2

這是我在某段時間使用libCURL編寫的一個骯髒的C++ HTTP fetcher。

它需要一個URL並返回一個字符串與獲取請求的內容。修改和口味:

/* 
* HttpFetcher.h 
*/ 
#ifndef _http_fetcher_ 
#define _http_fetcher_ 

#include <stdlib.h> 
#include <string> 

class HttpFetcher { 
public: 
    std::string simpleGetRequest(std::string url); 

private: 
    // Private methods to handle getting 
    struct MemoryStruct { 
    char *memory; 
    size_t size; 
    }; 
    static size_t WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data); 

}; 

#endif // ifndef _http_fetcher_ 

/* 
* HttpFetcher.cpp 
* Much of this is quite similar to examples on the libcURL site 
*/ 

#include "HttpFetcher.h" 
#include "curl.h" 
#include "easy.h" 
#include <iostream> 


size_t HttpFetcher::WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data) 
{ 
    size_t realsize = size * nmemb; 
    struct MemoryStruct *mem = (struct MemoryStruct *)data; 

    mem->memory = (char*)realloc(mem->memory, mem->size + realsize + 1); 
    if (mem->memory == NULL) { 
    /* out of memory! */ 
    printf("not enough memory (realloc returned NULL)\n"); 
    exit(EXIT_FAILURE); 
    } 

    memcpy(&(mem->memory[mem->size]), ptr, realsize); 
    mem->size += realsize; 
    mem->memory[mem->size] = 0; 

    return realsize; 
} 



std::string HttpFetcher::simpleGetRequest(std::string url) 
{ 
    std::string toReturn = ""; 
    CURL *curl = NULL; 

    struct MemoryStruct chunk; 
    chunk.memory = (char*)malloc(1); 
    chunk.size = 0; 

    CURLcode res; 
    curl = curl_easy_init(); 
    if(curl) { 
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); 
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &WriteMemoryCallback); 
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&chunk); 
    // Some requests fail without a user agent. 
    curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0"); 

    res = curl_easy_perform(curl); 

    curl_easy_cleanup(curl); 

    toReturn = std::string(chunk.memory); 
    } 

    free(chunk.memory); 

    return toReturn; 
} 
+0

感謝您的快速回復。 – Deany