c++ - 尝试维基百科查询时出现 CURLPP 400 错误请求

标签 c++ wikipedia curlpp

我想使用以下 URL 提取维基百科页面的摘要:

https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Stack%20Overflow

我也在使用 CURLPP 库来实现这个目标:

#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>
#include <curlpp/Exception.hpp>
#include <sstream>
#include <fstream>
#include <iostream>

using namespace std;

int main()
{
    string query = "Aldous Huxley";
    curlpp::Cleanup myCleanup;
    std::ostringstream os;
    string url = "https://en.wikipedia.org/w/api.php?format=xml&action=query&prop=extracts&exintro=&explaintext=&titles=";
    os << curlpp::options::Url(std::string( url + query));
    
    string asAskedInQuestion = os.str();
    cout << asAskedInQuestion << endl;
   return 0;
}

输出

每次我尝试查询 Aldous Huxley 时,我都会收到以下错误:

<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx/1.9.4</center>
</body>
</html>

任何其他查询都正常工作。为什么会出现此错误? 例如,当我尝试无政府主义时,我得到以下输出:

<api batchcomplete="">
<query>
<pages>
<page _idx="12" pageid="12" ns="0" title="Anarchism">
<extract xml:space="preserve">
Anarchism is a political philosophy that advocates stateless societies often defined as self-governed voluntary institutions, but that several authors have defined as more specific institutions based on non-hierarchical free associations. Anarchism holds the state to be undesirable, unnecessary, or harmful. While anti-statism is central, anarchism entails opposing authority or hierarchical organisation in the conduct of human relations, including, but not limited to, the state system. As an anti-dogmatic philosophy, anarchism draws on many currents of thought and strategy. Anarchism does not offer a fixed body of doctrine from a single particular world view, instead fluxing and flowing as a philosophy. There are many types and traditions of anarchism, not all of which are mutually exclusive. Anarchist schools of thought can differ fundamentally, supporting anything from extreme individualism to complete collectivism. Strains of anarchism have often been divided into the categories of social and individualist anarchism or similar dual classifications. Anarchism is usually considered a radical left-wing ideology, and much of anarchist economics and anarchist legal philosophy reflect anti-authoritarian interpretations of communism, collectivism, syndicalism, mutualism, or participatory economics.
</extract>
</page>
</pages>
</query>
</api>

最佳答案

您需要对查询字符串进行 URL 编码。使用例如

string query = "Aldous%20Huxley";

关于c++ - 尝试维基百科查询时出现 CURLPP 400 错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32522207/

相关文章:

程序中的 C++ 错误

c++ - 单独文件中的函数实现

android - 如何将维基百科内容检索到 Android 应用程序中?

xml - 将大型 XML 文件切割成小块

c++ - 使用 curlpp 获得响应

c++ - 对短字符串编码的有理数执行算术运算时 float 的简单替代方法

c++ - 保留预处理器定义

java - 如何使用 Wikipedia API 提取/解析我要查找的链接?

c++ - 使用 CMake 在项目中链接 curl