我有一个问题。我有以下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
变量没有被页面接收到呢?如何解决这个问题?
utf-8
前面加上charset=
。另外请注意,UTF-8 是application/json
的默认编码,因此甚至不需要指定它。 - Olivier