【问题标题】:Laravel 8 HTTP Client - How to send a string in a POST requestLaravel 8 HTTP 客户端 - 如何在 POST 请求中发送字符串
【发布时间】:2022-07-14 11:02:13
【问题描述】:

我需要向需要字符串作为参数的 API 发送 POST 请求。我使用 Laravel 的 HTTP 客户端发出请求,但 data 格式是一个数组。

$response = Http::acceptJson()->withHeaders([
                'Connection' => 'keep-alive',
                'Content-Type' => 'application/json'
            ])->post($url, [ "NtpcFQj9lQQoWuztFpssFoSQTAwbGReBbl6nc4HKYLEm" ]);

这是来自Illuminate\Http\Client\PendingRequestpost() 函数

/**
     * Issue a POST request to the given URL.
     *
     * @param  string  $url
     * @param  array  $data
     * @return \Illuminate\Http\Client\Response
     */
    public function post(string $url, array $data = [])
    {
        return $this->send('POST', $url, [
            $this->bodyFormat => $data,
        ]);
    }

我从带有Http::dd()的请求中得到的格式

^ Illuminate\Http\Client\Request {#1381 ▼
  #request: GuzzleHttp\Psr7\Request {#1378 ▼
    -method: "POST"
    -requestTarget: null
    -uri: GuzzleHttp\Psr7\Uri {#1366 ▶}
    -headers: array:6 [▼
      "Content-Length" => array:1 [▶]
      "User-Agent" => array:1 [▶]
      "Host" => array:1 [▶]
      "Accept" => array:1 [▼
        0 => "application/json"
      ]
      "Connection" => array:1 [▼
        0 => "keep-alive"
      ]
      "Content-Type" => array:1 [▼
        0 => "application/json"
      ]
    ]
    -headerNames: array:6 [▶]
    -protocol: "1.1"
    -stream: GuzzleHttp\Psr7\Stream {#1369 ▶}
  }
  #data: array:1 [▼
    0 => "NtpcFQj9lQQoWuztFpssFoSQTAwbGReBbl6nc4HKYLEm"
  ]
}

我需要的是data 具有以下格式:

^ Illuminate\Http\Client\Request {#1381 ▼
  #request: GuzzleHttp\Psr7\Request {#1378 ▼
    -method: "POST"
    -requestTarget: null
    -uri: GuzzleHttp\Psr7\Uri {#1366 ▶}
    -headers: array:6 [▼
      "Content-Length" => array:1 [▶]
      "User-Agent" => array:1 [▶]
      "Host" => array:1 [▶]
      "Accept" => array:1 [▼
        0 => "application/json"
      ]
      "Connection" => array:1 [▼
        0 => "keep-alive"
      ]
      "Content-Type" => array:1 [▼
        0 => "application/json"
      ]
    ]
    -headerNames: array:6 [▶]
    -protocol: "1.1"
    -stream: GuzzleHttp\Psr7\Stream {#1369 ▶}
  }
  #data: "NtpcFQj9lQQoWuztFpssFoSQTAwbGReBbl6nc4HKYLEm"
  ]
}

尝试将内容类型更改为“text/plain”,但字符串始终保留在数组中。

使用 HTTP 客户端仅在 data 内发送字符串的任何解决方案?另一个 PHP 库,我可以使用它来使用字符串类型的参数发出 POST 请求?

【问题讨论】:

  • 您不将其作为键/值对发送:->post($url, ['data' => 'NtpcFQj9lQQoWuztFpssFoSQTAwbGReBbl6nc4HKYLEm'])?你现在发送它的方式是一个索引数组[0 => ...],但作为关联数组发送['data' => ...]会导致data: 'NtpcFQj9lQQoWuztFpssFoSQTAwbGReBbl6nc4HKYLEm',我认为?
  • 或者我理解错了;你希望data 成为一个数组吗?我不确定使用string 作为->post() 的第二个参数是否有效,比如->post($url, 'NtpcFQj9lQQoWuztFpssFoSQTAwbGReBbl6nc4HKYLEm'),但也许也可以试试?
  • 您可以使用json返回结果并在最终解码

标签: php string http-post laravel-8


【解决方案1】:

你解决了吗?我目前有同样的问题

【讨论】:

    猜你喜欢
    • 2022-10-17
    • 1970-01-01
    • 2020-08-16
    • 2015-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多