Java POST 请求不发送变量

A. *_*ijk 6 php java post

我有个问题。我有以下 PHP 页面:

<?php

    header('Content-Type: application/json');
    
    echo $_POST["agentid"];

?>
Run Code Online (Sandbox Code Playgroud)

我的Java代码如下:

public String callWebpage(String strUrl, HashMap<String, String> data) throws InterruptedException, IOException {

    var objectMapper = new ObjectMapper();
    String requestBody = objectMapper
            .writeValueAsString(data);

    URL url = new URL(strUrl);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setDoOutput(true);
    con.getOutputStream().write(requestBody.getBytes("UTF-8"));
    String result = convertInputStreamToString(con.getInputStream());
    return result;
}
Run Code Online (Sandbox Code Playgroud)

要调用该函数,我使用以下几行:

var values = new HashMap<String, String>() {{
    put("agentid", String.valueOf(agentId));
}};

String jsonResponse = webAPI.callWebpage("https://www.test.org/test.php", values);
Run Code Online (Sandbox Code Playgroud)

这确实打印了页面的结果,但它给了我:

2021-02-28 00:40:16.735 Custom error: [8] Undefined index: agentid<br>2021-02-28 00:40:16.735 Error on line 5
Run Code Online (Sandbox Code Playgroud)

该页面是 HTTPS 并且我确实得到了响应,但是为什么我的agentid变量没有被页面接收到,我该如何解决这个问题?

jcc*_*ero 6

请考虑在您的 Java 连接设置中包含以下代码,以指示您在写入连接输出流之前发布 JSON 内容:

con.setRequestProperty("Content-Type", "application/json");
Run Code Online (Sandbox Code Playgroud)

无论如何,我认为问题出在您的 PHP 代码中:您正在尝试处理原始 HTTP 参数信息,而您正在接收 JSON 片段作为请求正文。

为了访问在 HTTP 请求中收到的原始 JSON 信息,您需要如下内容:

// Takes raw data from the request.
$json = file_get_contents('php://input');

// Converts it into a PHP object
$data = json_decode($json);

// Process information
echo $data->agentid; 
Run Code Online (Sandbox Code Playgroud)

请参阅此链接“php://input”以获取更多信息。

请注意,使用上述代码,您将向 Java 客户端返回一个字符串,尽管您指出header('Content-Type: application/json'),但它可能是导致任何问题的原因。