来自Google Search API的错误404

本文关键字:错误 API Google Search 来自 | 更新日期: 2023-09-27 18:00:02

我从下面的代码中得到一个404错误。我正在运行Visual C#速成版2010。字符串的查询部分是:

q%3dAction%2bMotivation%2c%2bInc.%2bSouth%2bSan%2bFrancisco%2b%26alt%3djson%26start%3d0%26num%3d10"

string searchString =       
    "https://www.googleapis.com/customsearch/v1%3fkey%3d{APIkey}%26cx%3d{cxkey}%26q%3dAction%2bMotivation%2c%2bInc.%2bSouth%2bSan%2bFrancisco%2b%26alt%3djson%26start%3d0%26num%3d10";
WebRequest myRequest = WebRequest.Create(searchString);
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

来自Google Search API的错误404

你逃避得太多了。您应该只转义查询值,而不是键/值对分隔符。所以URL应该是这样的:

string url = string.Format(
    "https://www.googleapis.com/customsearch/v1?key={0}&cx={1}&q={2}",
    HttpUtility.UrlEncode(apiKey),
    HttpUtility.UrlEncode(cxKey),
    HttpUtility.UrlEncode(query));

(其中query原始查询,例如"Action Motivation股份有限公司"(我还没有检查您使用的转义序列实际代表了什么。)