我有进行网址请求的方法:
public function send($httpUrl, $httpParams = [], $httpHeader = [], $waitForResponse = false)
{
if ($httpParams) {
foreach ($httpParams as $key => &$val) {
if (is_array($val)) $val = implode(',', $val);
$post_params[] = $key . '=' . urlencode($val);
}
$post_string = implode('&', $post_params);
}
$parts = parse_url($httpUrl);
if ($parts['scheme'] == 'https') {
$parts['port'] = 5371; // wymagany port dla nginx w php v 7.1
$parts['url'] = "ssl://" . $parts['host'];
}
if (!$httpHeader['Method'])
$httpHeader['Method'] = "GET";
$fp = fsockopen($parts['url'],
isset($parts['port']) ? $parts['port'] : 80,
$errno, $errstr, 30);
$out = $httpHeader['Method'] . " " . $parts['path'] . " HTTP/1.1\r\n";
$out .= "Host: " . $parts['host'] . "\r\n";
foreach ($httpHeader AS $k => $w) {
if ($k == 'Method') continue;
$out .= "$k: $w\r\n";
}
$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
$out .= "Content-Length: " . strlen($post_string) . "\r\n";
$out .= "Connection: Close\r\n\r\n";
if (isset($post_string)) $out .= $post_string;
fwrite($fp, $out);
if ($waitForResponse) {
$odpowiedz = '';
while (!feof($fp)) {
$odpowiedz .= fgets($fp, 128);
}
} else {
$odpowiedz = true;
}
fclose($fp);
return $odpowiedz;
}
问题是它返回带有标题的响应 喜欢:
string(746) "HTTP/1.1 200 OK Date: Wed, 16 Oct 2019 12:17:57 GMT Server: Apache Set-Cookie: PHPSESSID=960d6fee4a2fcdc25520f75b2cd5d11a; path=/ Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate Pragma: no-cache Access-Control-Allow-Headers: Content-Type, Authorization Access-Control-Allow-Origin: * Access-Control-Allow-Methods: GET, POST, PUT, DELETE Content-Length: 269 Connection: close Content-Type: application/json;charset=utf-8 {"ankieta_id":6,"pytanie":"Pierwsze pytanie - dzia\u0142a?","link":"https:\/\/www.infirma.pl\/ankiety\/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhbmtpZXRhSWQiOjYsImtsaWVudElkIjoxLCJ1enl0a293bmlrSWQiOjEsImV4cCI6MTU3MzgyMDI3N30.4zXu0e9ns4OZC0f5ITD9XoTd8TS3zUROOSVjiKnebdU"}"
我只希望标头不是json字符串。
答案 0 :(得分:0)
使用fread()来读取响应。使用以下代码更改fgets部分:
while (!feof($fp)) {
$odpowiedz .= fread($this->socket, 1024);
}
然后,您可以使用以下代码仅剥离身体部位:
$crlf = "\r\n";
$position = strpos($response, $crlf.$crlf);
$content = substr($response, $position + 2 * strlen($crlf));
答案 1 :(得分:0)