如何正确发送/接收HTTP POST中的URL参数?

0 投票
2 回答
2765 浏览
提问于 2025-04-17 22:05

我正在使用cakephp 2.4.5。我想通过HTTP POST发送带有URL参数的数据。我使用的是python 2.7的请求模块来发送这个HTTP POST。请假设我发送的数据格式是正确的,因为我已经测试过那部分。

URL_post = http://127.0.0.1/webroot/TestFunc?identity_number=S111A/post
r = requests.post(URL_post, payload)

在cakephp那边,控制器大概是这样的;

public function TestFunc($id=null)
{
    $identity_number = $this->request->query['identity_number'];  
    $this->request->data['Model']['associated_id']=$identity_number;
    $this->Model->saveAll($this->request->data, array('deep' => true));   
}

我测试过,发现查询参数没有正确接收到。不过,如果我不使用HTTP POST,而是直接使用普通的URL,查询参数就能正确接收到。

我到底做错了什么呢?

2 个回答

1

请查看这个链接:http://docs.python-requests.org/en/latest/user/quickstart/#passing-parameters-in-urls

payload = {"identity_number": "S111A/post"}
URL_post = "http://127.0.0.1/webroot/TestFunc"
req = requests.post(URL_post, params=payload)
print(req.status_code)
1

网址中的查询部分发送得很正确:

import requests

requests.post('http://localhost/webroot/TestFunc?identity_number=S111A/post',
              {'Model': 'data'})

请求

POST /webroot/TestFunc?identity_number=S111A/post HTTP/1.1
Host: localhost
User-Agent: python-requests/2.2.1 CPython/3.4 Linux/3.2
Accept: */*
Accept-Encoding: gzip, deflate, compress
Content-Type: application/x-www-form-urlencoded
Content-Length: 10

Model=data

你也可以使用 params 来发送请求:

requests.post('http://localhost/webroot/TestFunc',
              data={'Model': 'data'},
              params={'identity_number': 'S111A/post'})

唯一的区别是 S111A/post 被发送成了 S111A%2Fpost(最后的网址是一样的)。

撰写回答