【发布时间】: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\PendingRequest 的post() 函数
/**
* 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