Windows下将CURL POST请求转换为Python脚本时遇到问题
问题出在请求格式不匹配!
嘿,我一眼就看出问题所在了:你的curl命令发送的是JSON格式的请求体,但你写的Python脚本用urlencode处理数据,实际上发送的是**表单编码(application/x-www-form-urlencoded)**的内容,服务器端期望接收JSON格式的请求,所以无法正确解析你的输入,才返回了空的[]。
修正后的Python脚本
直接使用json模块将字典序列化为JSON字符串,并设置正确的Content-Type请求头,就能和原curl命令的行为一致了:
import json from urllib.request import Request, urlopen url = 'http://192.168.0.106:8080/parser' post_data = {"query": "NEW YORK"} # 把字典转成JSON字符串,再编码为字节 json_data = json.dumps(post_data).encode('utf-8') # 创建请求时指定Content-Type为application/json,告诉服务器我们发的是JSON request = Request(url, data=json_data, headers={'Content-Type': 'application/json'}) response = urlopen(request).read().decode() print(response)
更简洁的替代方案(用requests库)
如果不想用原生的urllib,可以用更友好的requests库(需要先通过pip install requests安装),代码会更简洁直观:
import requests url = 'http://192.168.0.106:8080/parser' post_data = {"query": "NEW YORK"} # 直接用json参数传入字典,requests会自动帮你序列化为JSON并设置正确的请求头 response = requests.post(url, json=post_data) print(response.text)
补充说明
- 你的原curl命令中,
-d "{\"query\": \"NEW YORK\"}"本质是发送JSON数据,部分curl版本会自动为你设置Content-Type: application/json请求头,所以服务器能正确识别。 - 而你原来的代码用
urlencode生成的是query=NEW+YORK这样的表单格式数据,和服务器期望的JSON格式完全不匹配,自然得不到正确的返回结果。
内容的提问来源于stack exchange,提问作者Zaid Khan




