最近遇到一个低概率问题, 具体问题就不详细说了, 只简要说说: 拉取某接口失败(低概率), 做重复拉取一次的动作, 第二次成功, 但后台给客户端返回的值始终不对, 花了一番功夫, 才查出原因。 这个问题非常隐蔽, 来看看:
#include <iostream>
#include <stdio.h>
#include "curl.h" // 请自己负责添加curl头文件和库
using namespace std;
static size_t downloadCallback(void *buffer, size_t sz, size_t nmemb, void *writer)
{
string* psResponse = (string*) writer;
size_t size = sz * nmemb;
psResponse->append((char*) buffer, size);
return sz * nmemb;
}
int main()
{
string strUrl = "http://www.baidu.com";
string strTmpStr = "xxxxxx"; // 假设这是第一次拉取失败时, 得到的响应
// 第二次拉取
CURL *curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 2);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, downloadCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &strTmpStr); // 串扰,串扰,串扰!!!
CURLcode res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
string strRsp;
if (res != CURLE_OK)
{
strRsp = "error";
}
else
{
strRsp = strTmpStr;
}
printf("strRsp is |%s|\n", strRsp.c_str());
return 0;
}
结果:
strRsp is |xxxxxx<!DOCTYPE html><!--STATUS OK-->
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<link rel="dns-prefetch" href="//s1.bdstatic.com"/>
<link rel="dns-prefetch" href="//t1.baidu.com"/>
<link rel="dns-prefetch" href="//t2.baidu.com"/>
<link rel="dns-prefetch" href="//t3.baidu.com"/>
<link rel="dns-prefetch" href="//t10.baidu.com"/>
<link rel="dns-prefetch" href="//t11.baidu.com"/>
<link rel="dns-prefetch" href="//t12.baidu.com"/>
<link rel="dns-prefetch" href="//b1.bdstatic.com"/>
<title>百度一下,你就知道</title>
<link href="http://s1.bdstatic.com/r/www/cache/stat..............................................(我省略了)
看看, strTmpStr果然被串扰, 如果是在封装很多层的程序中, 串扰问题就比较难查了。 我遇到过很多类似的问题了, 如上问题的解决还算顺利。 解决办法也很简单, 使用前清空即可。
不多说。