PHP处理HAPI-FHIR客户端POST请求的HTTP响应写法是否正确?
PHP服务端HTTP响应格式错误导致HAPI-FHIR客户端解析失败并重试
问题场景
PHP服务端返回的HTTP响应触发HAPI-FHIR客户端抛出异常,报错信息如下:
Failed delivery for (MessageId: ID: on ExchangeId: <..>). caught: ca.uhn.fhir.rest.client.exceptions.FhirClientConnectionException: HAPI-1359: Failed to parse response from server when performing POST to URL
伴随DataFormatException:HAPI-1861: Failed to parse JSON encoded FHIR content: HAPI-1857: Did not find any content to parse
客户端因此每隔一小时重复发送相同Bundle消息重试。
问题代码
用户编写的PHP响应代码:
$_http_status_line = "HTTP/1.1 201 Created "; $_date_string = make_date_string_reponse($_debug_level); $_general_header = $_date_string . "; "; $_etag_header = "ETag: W/\"1\"; "; $_location_header = "Location: https://<some.url>/; "; $_response_header = $_etag_header . " " . $_location_header . " "; $_last_modified_date_string = make_date_string_reponse($_debug_level); $_content_type_header = "Content-Type: application/fhir+json;charset=utf-8; "; $_last_modified_header = "Last-Modified: {$_last_modified_date_string}; "; $_entity_header = $_content_type_header . $_last_modified_header . " "; $_http_header = $_general_header . $_response_header . $_entity_header . "\n" ; $_http_response = $_http_status_line . $_http_header; header($_http_response);
生成的错误响应:
HTTP/1.1 201 Created Tue, 12 Dec 2023 04:54:37 GMT; ETag: W/"1"; Location: https://<some.url>/; Content-Type: application/fhir+json;charset=utf-8; Last-Modified: Tue, 12 Dec 2023 04:54:37 GMT;
错误分析
- HTTP头设置方式完全错误:PHP的
header()函数要求每个HTTP头单独调用设置,状态行与响应头需分离。用户将状态行、所有响应头拼接成一个字符串传入header(),导致客户端无法识别正确的头结构——所有头被错误附加在状态行后,不符合HTTP协议"状态行→换行→每个头单独一行→双换行→响应体"的格式规范。 - 缺少FHIR格式的响应体:HAPI-FHIR客户端收到201响应时,期望获取创建后的FHIR资源JSON内容。当前响应无任何响应体,触发"Did not find any content to parse"错误。
修复方案
1. 正确设置HTTP响应头
使用header()函数单独设置每个响应头,状态行单独处理:
// 设置状态码 header("HTTP/1.1 201 Created"); // 生成日期字符串 $_date_string = make_date_string_reponse($_debug_level); $_last_modified_date_string = make_date_string_reponse($_debug_level); // 逐个设置响应头 header("Date: {$_date_string}"); header("ETag: W/\"1\""); header("Location: https://<some.url>/"); header("Content-Type: application/fhir+json;charset=utf-8"); header("Last-Modified: {$_last_modified_date_string}");
2. 返回FHIR格式的响应体
设置完所有头后,输出创建成功的FHIR资源JSON(至少是符合FHIR规范的操作响应),示例:
// 返回FHIR标准操作响应 echo json_encode([ "resourceType" => "OperationOutcome", "issue" => [ [ "severity" => "information", "code" => "informational", "details" => ["text" => "Resource created successfully"] ] ] ]);
验证说明
修复后,HTTP响应将符合标准格式:
HTTP/1.1 201 Created Date: Tue, 12 Dec 2023 04:54:37 GMT ETag: W/"1" Location: https://<some.url>/ Content-Type: application/fhir+json;charset=utf-8 Last-Modified: Tue, 12 Dec 2023 04:54:37 GMT {"resourceType":"OperationOutcome","issue":[{"severity":"information","code":"informational","details":{"text":"Resource created successfully"}}]}
客户端将能正确解析响应头与响应体,停止重试行为。
内容的提问来源于stack exchange,提问作者evert
相关产品推荐
相关产品推荐

