为何$_POST超全局变量无法获取HTTP请求实体中的数据?
问题原因与解决方案
你的POST参数无法被PHP识别,核心原因是请求没有设置正确的Content-Type头,且参数格式不符合PHP$_POST的解析规则。
修正后的Kotlin代码
val client = HttpClients.createDefault() val postReq = HttpPost("http://VALID_DOMAIN/app/posttest.php") // 构造表单参数列表 val formParams = arrayListOf<NameValuePair>() formParams.add(BasicNameValuePair("tst", "1234")) // 生成符合表单编码的实体,自动设置Content-Type为application/x-www-form-urlencoded postReq.entity = UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8) // 执行请求并读取响应 val response = client.execute(postReq) { EntityUtils.toString(it.entity, StandardCharsets.UTF_8) }
为什么原来的代码不行?
你直接用HttpEntities.create("tst=1234")创建的实体,默认的Content-Type是text/plain。PHP只会自动解析application/x-www-form-urlencoded或multipart/form-data类型的请求体到$_POST数组,text/plain类型的内容只会留在原始请求流里,无法通过$_POST获取。
备选方案(手动设置头)
如果一定要用字符串构造请求体,需要手动指定Content-Type:
val client = HttpClients.createDefault() val postReq = HttpPost("http://VALID_DOMAIN/app/posttest.php") val entity = StringEntity("tst=1234", StandardCharsets.UTF_8) postReq.entity = entity // 必须设置这个头,PHP才能识别为表单参数 postReq.setHeader("Content-Type", "application/x-www-form-urlencoded") val response = client.execute(postReq) { EntityUtils.toString(it.entity, StandardCharsets.UTF_8) }
调试小技巧
可以在PHP代码中添加一行,查看原始请求体,确认参数是否正确发送:
var_dump(file_get_contents('php://input'));
内容的提问来源于stack exchange,提问作者GPorubanTKK
相关产品推荐
相关产品推荐

