如何在Laravel中获取HTTP请求正文内容?

时间:2021-04-30 23:59:14

I am making an API with Laravel 5 and I'm testing it with PHPUnit. I need to test legacy functionality for compatibility, which is an XML POST. As of right now, my first test looks like:

我正在用Laravel 5做一个API,我正在用PHPUnit测试它。我需要测试遗留功能的兼容性,这是一个XML帖子。就目前而言,我的第一个测试是:

public function testPostMessages()
{
    $response = $this->call('POST', 'xml');

    $this->assertEquals(200, $response->getStatusCode());
}

This is passing just fine. Next on my list is actually sending the XML data with the POST. So for my second test, I have:

这一切都很顺利。我列表中的下一个实际上是用POST发送XML数据。所以我的第二次测试是:

public function testPostMessagesContent()
{
    $response = $this->call('POST', 'xml');

    $this->assertTrue(is_valid_xml($response->getContent()));
}

This test fails. However, I am not sending my XML data. How do I send my XML?
Now, after that I need to add in the functionality to get the content from the request. I know there is a Request object that I can interact with but I don't exactly know which method to call on it. How do I get my XML from inside my controller?

这个测试失败。但是,我没有发送XML数据。如何发送XML?现在,在此之后,我需要添加功能以从请求中获取内容。我知道有一个请求对象可以与之交互,但我不知道调用它的方法。如何从控制器中获取XML ?


Update #1

I was able to get some results in the meantime. My current test looks like this:

在此期间我得到了一些结果。我现在的测试是这样的:

public function testPostMessagesContent()
{
    $response = $this->call('POST', 'xml', array('key' => 'value'), array(), array(), array('content' => 'content'));
    $this->assertContains('~', $response->getContent());
}

I only have the tilde there because I know it won't match so that I can see the whole response. In XmlController.php I have:

我只写了斜线因为我知道它不匹配这样我就能看到整个响应。在XmlController。php有:

class XmlController extends Controller {
public function index(Request $request)
{
    return $request;
    }
}

My output from PHPUnit is as follows:

PHPUnit输出如下:

1) XmlTest::testPostMessagesContent
Failed asserting that 'POST xml HTTP/1.1
Accept:          text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Charset:  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Accept-Language: en-us,en;q=0.5
Content-Type:    application/x-www-form-urlencoded
Host:            localhost
User-Agent:      Symfony/2.X
' contains "~".

Where are my parameters and my content? I feel like I am simply just using call() incorrectly.

我的参数和内容在哪里?我觉得我只是在不正确地使用call()。


Update #2

I updated my controller to use Request:all() like so:

我更新了我的控制器来使用Request:all() like so:

class XmlController extends Controller
{
    public function index()
   {
        $content = Request::all();
        return $content;
    }
}

This returned my key-value pair, but not the content.

这返回了键值对,但不返回内容。

1) XmlTest::testPostMessagesContent
Failed asserting that '{"key":"value"}' contains "~".

Key-value pairs are good; it's progress. However, what I really need is the content since I'll be receiving that data in the content portion of the request. If I use Request::getContent() I get back a blank string. Here's my call in the test:

键值对是好的;它的进步。但是,我真正需要的是内容,因为我将在请求的内容部分接收数据。如果我使用Request::getContent(),我会得到一个空字符串。这是我在测试中的电话:

$response = $this->call('POST', 'xml', array('key' => 'value'), array(), array(), array('content' => 'content'));

Here's my test results:

这是我的测试结果:

1) XmlTest::testPostMessagesContent
Failed asserting that '' contains "~".

Update #3

I am not able to get the content body of an HTTP Request at all. Since XML wasn't working, I moved forward with the REST part of my API, which uses JSON. Here's one of my tests:

我根本无法获得HTTP请求的内容主体。由于XML不工作,所以我使用了我的API的REST部分,它使用了JSON。下面是我的一个测试:

public function testPostMessagesContent()
{
    $response = $this->call('POST', 'messages', ['content' => 'content']);

    $this->assertEquals('saved!', $response->getContent());
}

This test passes. If I use curl, I get a successful call as well:

这个测试通过。如果我使用旋度,我也会得到一个成功的电话:

curl -X POST -d "content=my_new_content" "http://localhost:8000/messages"

This returns 'saved!' That's awesome, but if I try to use curl in a standalone PHP script (to simulate a client), this is what is returned:

这将返回“得救了!“这太棒了,但是如果我尝试在一个独立的PHP脚本中使用curl(来模拟客户端),就会得到这样的结果:

Array ( [url] => http://localhost:8000/messages [content_type] => text/html; charset=UTF-8 [http_code] => 302 [header_size] => 603 [request_size] => 118 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.063977 [namelookup_time] => 0.000738 [connect_time] => 0.000866 [pretransfer_time] => 0.000943 [size_upload] => 12 [size_download] => 328 [speed_download] => 5126 [speed_upload] => 187 [download_content_length] => -1 [upload_content_length] => 12 [starttransfer_time] => 0.057606 [redirect_time] => 0 [certinfo] => Array ( ) [primary_ip] => ::1 [primary_port] => 8000 [local_ip] => ::1 [local_port] => 63248 [redirect_url] => http://localhost:8000 [request_header] => POST /messages HTTP/1.1 Host: localhost:8000 Accept: */* Content-type: text/xml Content-length: 12 ) Redirecting to http://localhost:8000. 

This is my curl command adding the POST fields:

这是我的curl命令,添加了POST字段:

curl_setopt($ch, CURLOPT_POSTFIELDS, 'content=test');

It seems to me that POSTFIELDS is getting added to the body of the request. In this case, I still have the same problem. I am not able to get body content of my HTTP headers. After commenting out my validation, I get:

在我看来,POSTFIELDS正在添加到请求的主体。在这种情况下,我仍然有同样的问题。我无法获得HTTP头的正文内容。在注释了我的验证之后,我得到:

Array ( [url] => http://localhost:8000/messages [content_type] => text/html; charset=UTF-8 [http_code] => 200 [header_size] => 565 [request_size] => 118 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.070225 [namelookup_time] => 0.000867 [connect_time] => 0.00099 [pretransfer_time] => 0.001141 [size_upload] => 12 [size_download] => 6 [speed_download] => 85 [speed_upload] => 170 [download_content_length] => -1 [upload_content_length] => 12 [starttransfer_time] => 0.065204 [redirect_time] => 0 [certinfo] => Array ( ) [primary_ip] => ::1 [primary_port] => 8000 [local_ip] => ::1 [local_port] => 63257 [redirect_url] => [request_header] => POST /messages HTTP/1.1 Host: localhost:8000 Accept: */* Content-type: text/xml Content-length: 12 ) saved!

So I have my 'saved!' message. Great! But, in my database now I have a blank row. Not great. It is still not seeing the body content, just the headers.

所以我得到了我的“拯救”!的消息。太棒了!但是,现在我的数据库中有一个空行。不是很好。它仍然看不到正文内容,只有标题。


Answer Criteria

I'm looking for the answers to these questions:

我在寻找这些问题的答案:

  1. Why can't I get the body content of my request?
  2. 为什么我不能得到我的请求的身体内容?
  3. How do I get the body content of my request?
  4. 我如何获得我的请求的正文内容?

3 个解决方案

#1


54  

Inside controller inject Request object. So if you want to access request body inside controller method 'foo' do the following:

控制器内部注入请求对象。所以如果你想在控制器方法foo中访问请求体做以下事情:

public function foo(Request $request){
    $bodyContent = $request->getContent();
}

#2


3  

You can pass data as the third argument to call(). Or, depending on your API, it's possible you may want to use the sixth parameter.

您可以将数据作为调用()的第三个参数传递。或者,根据您的API,您可能希望使用第6个参数。

From the docs:

从文档:

$this->call($method, $uri, $parameters, $files, $server, $content);

#3


0  

I don't think you want the data from your Request, I think you want the data from your Response. The two are different. Also you should build your response correctly in your controller.

我不认为你想要数据来自你的请求,我认为你想要数据来自你的回应。这两个是不同的。另外,您应该在控制器中正确地构建您的响应。

Looking at the class in edit #2, I would make it look like this:

看看编辑#2中的类,我会让它看起来像这样:

class XmlController extends Controller
{
    public function index()
    {
        $content = Request::all();
        return Response::json($content);
    }
}

Once you've gotten that far you should check the content of your response in your test case (use print_r if necessary), you should see the data inside.

一旦您获得了这一点,您应该检查您的测试用例中的响应的内容(如果有必要使用print_r),您应该可以看到里面的数据。

More information on Laravel responses here:

更多关于Laravel回复的信息请点击这里:

http://laravel.com/docs/5.0/responses

http://laravel.com/docs/5.0/responses

#1


54  

Inside controller inject Request object. So if you want to access request body inside controller method 'foo' do the following:

控制器内部注入请求对象。所以如果你想在控制器方法foo中访问请求体做以下事情:

public function foo(Request $request){
    $bodyContent = $request->getContent();
}

#2


3  

You can pass data as the third argument to call(). Or, depending on your API, it's possible you may want to use the sixth parameter.

您可以将数据作为调用()的第三个参数传递。或者,根据您的API,您可能希望使用第6个参数。

From the docs:

从文档:

$this->call($method, $uri, $parameters, $files, $server, $content);

#3


0  

I don't think you want the data from your Request, I think you want the data from your Response. The two are different. Also you should build your response correctly in your controller.

我不认为你想要数据来自你的请求,我认为你想要数据来自你的回应。这两个是不同的。另外,您应该在控制器中正确地构建您的响应。

Looking at the class in edit #2, I would make it look like this:

看看编辑#2中的类,我会让它看起来像这样:

class XmlController extends Controller
{
    public function index()
    {
        $content = Request::all();
        return Response::json($content);
    }
}

Once you've gotten that far you should check the content of your response in your test case (use print_r if necessary), you should see the data inside.

一旦您获得了这一点,您应该检查您的测试用例中的响应的内容(如果有必要使用print_r),您应该可以看到里面的数据。

More information on Laravel responses here:

更多关于Laravel回复的信息请点击这里:

http://laravel.com/docs/5.0/responses

http://laravel.com/docs/5.0/responses