当我使用 cURL 获取网页时,它似乎没有以正确的格式编码或接收数据。还是 cURL 以标准格式获取网页,而应用程序必须解压缩/放气/编码输出?
我一直在尝试处理的网页之一将执行以下操作:
- 让我们变得可笑 - Redfoo
- 咆哮 - 凯蒂佩里
- 破坏球——麦莉·赛勒斯
- 说脏话 Jason Derulo Feat。双链大师
在我的浏览器中,上面的示例在设置为“Western ISO-8859-1”编码时显示。在 UTF-8 上,它可以像破折号一样正常工作。同样的场景出现在我的应用程序中。它适用于除此之外的每个破折号。
另一个例子是 wiki UTF-8 文章:http ://en.wikipedia.org/wiki/UTF-8
应用程序的输出如下(需要 10 个代表发布图像):http: //img21.imageshack.us/img21/7048/i23c.png
我的应用程序使用标准 cURL 复制到内存示例并进行了一些修改来测试 wiki 链接:
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <curl/curl.h>
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t
WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
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");
return 0;
}
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
int main(void)
{
CURL *curl_handle;
CURLcode res;
struct MemoryStruct chunk;
chunk.memory = (char*)malloc(1); /* will be grown as needed by the realloc above */
chunk.size = 0; /* no data at this point */
curl_global_init(CURL_GLOBAL_ALL);
/* init the curl session */
curl_handle = curl_easy_init();
/* specify URL to get */
curl_easy_setopt(curl_handle, CURLOPT_URL, "http://en.wikipedia.org/wiki/UTF-8");
/* send all data to this function */
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
/* we pass our 'chunk' struct to the callback function */
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
/* some servers don't like requests that are made without a user-agent
field, so we provide one */
curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
/* get it! */
res = curl_easy_perform(curl_handle);
/* check for errors */
if(res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
}
else
{
char * x = chunk.memory;
bool copyFlag = false;
bool waitFlag = false;
for(unsigned i = 0;i<chunk.size;i++)
{
if (copyFlag == true)
{
if (waitFlag == false)
{
if (*x == '>')
waitFlag = true;
}
else if (waitFlag == true)
{
if (*x == '<')
{
waitFlag = false;
copyFlag = false;
std::cout << std::endl;
}
else
std::cout<< *x;
}
}
else if (*(x+5) == '<' && *(x+6) == '/' && *(x+7) == 'a' && *(x+8) == '>' && *(x+9) == '<' && *(x+10) == '/' && *(x+11) == 't' && *(x+12) == 'd' && *(x+13) == '>')//</a></td>
{
copyFlag = true;
}
x++;
}
}
/* cleanup curl stuff */
curl_easy_cleanup(curl_handle);
if(chunk.memory)
free(chunk.memory);
/* we're done with libcurl, so clean it up */
curl_global_cleanup();
system("Pause");
return 0;
}
我可以看到控制台和调试器之间的区别,它们每个都只能解释某些字符集,尽管可以在 cURL 中进行不同的设置还是应该编写编码函数?如果是这样,我应该如何开始?