Java POST请求未发送变量。

6

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

<?php

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

?>

我的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;
}

为了调用该函数,我使用以下代码:

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

String jsonResponse = webAPI.callWebpage("https://www.test.org/test.php", values);

这确实打印了页面的结果,但是它给了我:
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

这个页面是HTTPS协议的,我已经得到了响应,但是为什么我的agentid变量没有被页面接收到呢?如何解决这个问题?

2个回答

7
请在Java连接设置中考虑包含以下代码,以指示您正在向连接输出流写入JSON内容之前进行POST操作:
con.setRequestProperty("Content-Type", "application/json");

无论如何,我认为问题出在你的PHP代码上:当你收到一个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; 

请查看此链接'php://input'了解更多信息。
请注意,使用上述代码将向Java客户端返回一个字符串,尽管您指定了header('Content-Type: application/json'),但这可能是任何问题的原因。

非常感谢您,@A.Vreeswijk。太好了!我很高兴听到答案有所帮助。非常感谢。 - jccampanero
1
你忘记在 utf-8 前面加上 charset=。另外请注意,UTF-8 是 application/json 的默认编码,因此甚至不需要指定它。 - Olivier

-2

我认为你正在使用HTTP请求。那么,如果该代码与下面的答案相同,请使用exec而不是POST


那我需要改变什么呢? - A. Vreeswijk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接