调用Google Custom Search API始终返回400状态码,代码排查求助
我编写了如下Python代码:
import requests import json # Define the API endpoint and necessary headers and parameters url = "https://www.googleapis.com/customsearch/v1" # url = "https://yande.re/post/similar" api_key = "replace with your api" headers = {"Content-Type": "image/jpeg"} params = {"type": "similar", "cx": "d47119ff66e004d6b", "key":api_key} # Read the image file and convert it to binary with open("C:\\Users\\Administrator\\Downloads\\theme\\3f559715-f407-47de-8540-1cd9e4fdc56c.jpg", "rb") as f: image_data = f.read() # Send the POST request response = requests.post(url, headers=headers, params=params, data=image_data) # Check the status code of the response if response.status_code == 200: print('ok') # Parse the JSON response data = json.loads(response.text) # Extract the relevant data from the response similar_images = data["similar_images"] else: print(response.status_code) print('no')
当使用Google Custom Search API的接口地址时,请求始终返回400状态码,执行结果为no;但切换为https://yande.re/post/similar接口时能正常获取返回结果。请问我的代码哪里存在问题?是否是URL设置错误?
你的代码针对Google Custom Search API存在多处不符合接口规范的问题,和yande.re接口的设计逻辑完全不同:
接口URL与请求方式错误:Google Custom Search API没有接收二进制图片的POST接口,你用的
https://www.googleapis.com/customsearch/v1是通用搜索接口,且该接口仅支持GET请求,不支持直接POST图片二进制数据。参数不匹配:你代码里的
type=similar是yande.re接口的参数,Google Custom Search API不存在该参数。若要做图片相似搜索,需要使用searchType=image指定搜索类型,再通过imgSimilarTo参数传入可公开访问的图片URL(而非本地图片二进制)。请求头错误:Google Custom Search API不需要设置
Content-Type: image/jpeg,因为它不接收二进制图片上传,正确的请求头应保持默认的application/json或application/x-www-form-urlencoded(GET请求时无需额外设置)。数据传递方式错误:Google Custom Search API不支持直接上传本地图片,你需要先将图片上传到某个公开的存储服务获取可访问的URL,再将该URL作为
imgSimilarTo参数传入GET请求。
修正后的示例代码(基于Google Custom Search API图片相似搜索规范):
import requests import json # Google Custom Search API 正确配置 url = "https://www.googleapis.com/customsearch/v1" api_key = "replace with your api" cx = "d47119ff66e004d6b" # 替换为你的图片公开URL public_image_url = "https://example.com/your-image.jpg" # 正确的参数配置 params = { "key": api_key, "cx": cx, "searchType": "image", "imgSimilarTo": public_image_url } # 发送GET请求 response = requests.get(url, params=params) if response.status_code == 200: print('ok') data = json.loads(response.text) # 提取搜索结果,Google返回的结构和yande.re不同,需根据实际字段调整 similar_images = data.get("items", []) else: print(response.status_code) print('no') # 打印响应内容查看具体错误信息 print(response.text)
内容的提问来源于stack exchange,提问作者Nguyễn Văn Mạnh

