使用CakePHP POST请求XML

时间:2014-04-07 03:17:34

标签: php xml cakephp post

我尝试使用CakePHP 2.3.8发布XML数据的POST请求,但我遇到了一些问题,我认为它处理的是授权问题。首先,我尝试做的是使用来自控制器中的动作的XML数据发出POST请求。此发布请求的操作应该在数据库中保存一个条目,这样我就知道POST请求已成功触发。什么都没有得救。

以下是两个动作和beforefilter。我确保允许访问beforefilter中的每个操作。 xml_post是我访问的操作,它触发XML post请求,receive_xml操作是在收到内容时应该在数据库中保存条目的操作。

public function beforeFilter() {
    parent::beforeFilter();
    $this->Auth->authorize = 'Controller';  
    $this->Auth->allow = array('*');
}

public function xml_post_test(){
    $data = array(
        'post' => array(
            'id' => 1,
            'title' => 'This is a test',
            'body' => 'Here is something for the body '
        )
    );

    App::uses('HttpSocket', 'Network/Http');
    $http = new HttpSocket();
    $xml_data = Xml::fromArray($data);
    $xml_string = $xml_data->asXML();
    $response = $http->post('http://localhost/tests/receive_xml', $xml_string);
    debug($response);
}

    //save an arbitrary entry in the database a POST request is received (just checking that the xml_post_test method is working
public function receive_xml(){
        if($this->request->is('post')){
            $this->loadmodel('TestTable');
            $this->TestTable->create();
            $this->TestTable->save(array('id' => '','data' => 'abc 123'));
        }
}

这是响应(调试)

object(HttpSocketResponse) {
    body => ''
    headers => array(
        'Date' => 'Mon, 07 Apr 2014 02:28:15 GMT',
        'Server' => 'Apache/2.4.4 (Unix) PHP/5.4.19 OpenSSL/1.0.1e mod_perl/2.0.8-dev Perl/v5.16.3',
        'X-Powered-By' => 'PHP/5.4.19',
        'Set-Cookie' => 'CAKEPHP=ddb8lvdvmqvrce9ve2eo5e61l5; expires=Mon, 07-Apr-2014 06:28:15 GMT; path=/; HttpOnly',
        'Location' => 'http://localhost/users/login',
        'Content-Length' => '0',
        'Connection' => 'close',
        'Content-Type' => 'text/html; charset=UTF-8'
    )
    cookies => array(
        'CAKEPHP' => array(
            'value' => 'ddb8lvdvmqvrce9ve2eo5e61l5',
            'expires' => 'Mon, 07-Apr-2014 06:28:15 GMT',
            'path' => '/',
            'httponly' => true
        )
    )
    httpVersion => 'HTTP/1.1'
    code => '302'
    reasonPhrase => 'Found'
    raw => 'HTTP/1.1 302 Found
Date: Mon, 07 Apr 2014 02:28:15 GMT
Server: Apache/2.4.4 (Unix) PHP/5.4.19 OpenSSL/1.0.1e mod_perl/2.0.8-dev Perl/v5.16.3
X-Powered-By: PHP/5.4.19
Set-Cookie: CAKEPHP=ddb8lvdvmqvrce9ve2eo5e61l5; expires=Mon, 07-Apr-2014 06:28:15 GMT; path=/; HttpOnly
Location: http://localhost/users/login
Content-Length: 0
Connection: close
Content-Type: text/html; charset=UTF-8

'
    context => array()
}

2 个答案:

答案 0 :(得分:0)

我可以在不查看细节的情况下看到一个问题 -

$this->Auth->allow = array('*');

应该是

$this->Auth->allow = array();

答案 1 :(得分:0)

您需要做的主要事情是将Content-Type标题设置为application/xml。您可能还希望将Accept-Type标头设置为相同的值(如果您需要XML响应而不使用Router::parseExtensions()方法,其中响应类型是从您在URL中传递的扩展名推断出来的。)