Skip to main content
 首页 » 编程设计

python之HTTP 请求在 cURL 中工作但在 urllib2.request 中不工作

2025年05月04日10jirigala

我有这个按预期运行的 cURL 命令:

curl -v -X POST -H "Api-Key:75b5cc58a5cdc0a583f91301cefedf0c" -H "Content-Type:application/x-www-form-urlencoded" "http://localhost:8080/app?client_id=ef5f7a03-58e8-48d7-a38a-abbd2696bdb6&grant_type=refresh_token&username=user1&password=password&refresh_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" 

此命令返回一个 JSON。

我尝试使用 urllib2 模拟此调用。

request_url = "http://localhost:8080/app" 
values = { 
        "client_id": "ef5f7a03-58e8-48d7-a38a-abbd2696bdb6", 
        "grant_type": "refresh_token", 
        "username": "user1", 
        "password": "password" 
        "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" 
    } 
 
data = urlencode(values) 
req = urllib2.Request(request_url, data) 
req.add_header("Api-Key", "75b5cc58a5cdc0a583f91301cefedf0c") 
req.add_header("Content-Type", "application/x-www-form-urlencoded") 
 
print request_url 
print req.get_data() 
print req.get_method() 
print req.get_full_url() 

这是我得到的输出:

http://localhost:8080/app 
username=user1&password=password&grant_type=refresh_token&refresh_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9&client_id=ef5f7a03-58e8-48d7-a38a-abbd2696bdb6 
POST 
http://localhost:8080/app 

上面的 urllib2.request 返回错误代码 401,这意味着我发送的 refresh_token 不正确。

这里可能出了什么问题?

请您参考如下方法:

cURL 命令将值作为查询参数作为 URL 的一部分传递。 urllib2 命令将值作为 POST 数据传递。你应该使用:

request_url = "http://localhost:8080/app" 
values = { 
        "client_id": "ef5f7a03-58e8-48d7-a38a-abbd2696bdb6", 
        "grant_type": "refresh_token", 
        "username": "user1", 
        "password": "password" 
        "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" 
    } 
request_url = request_url + "?" + urlencode(values) 
data = "" 
req = urllib2.Request(request_url, data) 
req.add_header("Api-Key", "75b5cc58a5cdc0a583f91301cefedf0c") 
req.add_header("Content-Type", "application/x-www-form-urlencoded") 

两点说明:

  1. 这使用带有空数据的 POST 方法来模仿 cURL 命令 也是一样的。
  2. 标准 OAuth 2.0 使用 POST 请求 token 端点(这似乎是这个请求的内容),所以你的 Python 代码是正确的