2013-12-16 49 views
3
int RiotAPI::getSite(std::string hostname) //RiotAPI is my class, almost empty atm 
{ 

if (wsa) //wsa is true, dont mind this. 
{ 
    ZeroMemory(&hints, sizeof(hints)); 
    hints.ai_family = AF_UNSPEC; 
    hints.ai_protocol = IPPROTO_TCP; 
    hints.ai_socktype = SOCK_STREAM; 

    errcode = getaddrinfo(hostname.c_str(), HTTPPORT, &hints, &result); //HTTPPORT defined as "80" <- string 
    if (errcode != 0) 
    { 
     printf("getaddrinfo() failed error: %d\n", errcode); 
    } 
    else 
     printf("getaddrinfo success\n"); 

    /*for (ptr=result; ptr != NULL; ptr->ai_next) 
    { 
     cSock = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); 
     if (cSock == INVALID_SOCKET) 
     { 
      printf("Socket creating failed.\n"); 
     } 
    }*/ 

    cSock = socket(result->ai_family, result->ai_socktype, result->ai_protocol); //didnt bother looping through results because the web address only returns 1 IP 

    errcode = connect(cSock, result->ai_addr, (int)result->ai_addrlen); 
    if (errcode != 0) 
     printf("Could not connect to the server"); 
    else{ 
    char request [] = "GET /api/lol/na/v1.1/summoner/by-name/RiotSchmick?api_key=<MY_API_KEY> HTTP/1.0\r\n"; 
    send(cSock, request, (int)strlen(request), 0); 

    char output [256]; 
    int bytesrecv = 0; 
    //char * cmp = "{\"id\":585897,\"name\":\"RiotSchmick\",\"profileIconId\":583,\"summonerLevel\":30,\"revisionDate\":1387143444000,\"revisionDateStr\":\"12/15/2013 09:37 PM UTC\"}"; 
    bytesrecv = recv(cSock, output, 255, 0); 
    printf("Bytes read: %d\n", bytesrecv); 
    printf("Output string: %s\n", output); 
    } 
} 
    return 0; 
} 

我一直在試圖編寫一個使用Riot Games API(英雄聯盟)的程序。WinSock2 HTTP GET使用方法

我的代碼應該可以正常工作,我嘗試從我的朋友服務器獲取網頁並且它工作,但它是索引。 (我用 「GET HTTP/1.0 \ r \ n」)

如果我想獲得此URL的內容:

http://prod.api.pvp.net/api/lol/na/v1.1/summoner/by-name/RiotSchmick?api_key=<here_goes_my_api_key> 

我不應該這樣進行:

1)連接到htt://prod.api.pvp.net

2)發送「GET /api/lol/na/v1.1/summoner/by-name/RiotSchmick?api_key= HTTP/1.0 \ r \ n 「

3)recv()直到返回0,然後打印出緩衝區(我不這樣做在我的公司雖然,我試圖收到255字節,看看它是否工作)

問題是,它只是坐在recv()函數(塊?)。 我的GET請求有問題嗎?

這裏的API信息頁: http://i.imgur.com/yXr5BYx.png

我曾嘗試使用我的請求,報頭,但同樣的事情,的recv()只是坐在那裏。

我也試過這樣:

char buffer [2048]; 
recv(cSock, buffer, 2047, 0); 
printf("Output string: %s\n", buffer); 

此代碼返回完全的頁面(不是所有的2048個字節都充滿雖然):

雖然這只是返回3個隨機字符jibberish。

std::string output = ""; 
char buffer [128]; 
//int bytesrecv = 0; 

while (recv(cSock, buffer, 127, 0) > 0) 
{ 
    output += buffer; 
} 
printf("Output string: %s\n", output); 

回答

1

你的GET請求是不完整的,最低限度它需要以一個空行結束......即\r\n\r\n末。但你可能會遇到其他問題,如需要一個Host標題,如果服務器正在服務多個域...

+0

是的,我確實在最後修復\ r \ n \ r \ n ...然後代碼下面有兩個問題。第二部分是什麼意思? – user2699298

+0

讓我們假設一個Web服務器託管幾個不同的域,如果您的GET請求要求在/的默認頁面,然後Web服務器知道您指的是哪個域的唯一方法是通過主機頭。即使它是HTTP/1.1標頭,許多服務器仍然需要它。 recv阻塞指示服務器等待您完成請求... – mark

+0

但是他們會在API信息中指定它們,對嗎?我在第一篇文章中添加了API文檔的圖像。 – user2699298