如何在Java中发送正确的HTTP PUT请求
我想使用Philips HUE Api用Java关闭我的灯。 为此,我有以下API: 这将返回:如何在Java中发送正确的HTTP PUT请求,java,http,http-put,philips-hue,Java,Http,Http Put,Philips Hue,我想使用Philips HUE Api用Java关闭我的灯。 为此,我有以下API: 这将返回: { "state": { "on": true, "bri": 178, "hue": 41044, "sat": 56, "effect": "none", "xy": [ 0
{
"state": {
"on": true,
"bri": 178,
"hue": 41044,
"sat": 56,
"effect": "none",
"xy": [
0.3313,
0.3447
],
"ct": 181,
"alert": "select",
"colormode": "ct",
"mode": "homeautomation",
"reachable": true
},
"swupdate": {
"state": "noupdates",
"lastinstall": "2020-07-03T12:17:24"
},
"type": "Extended color light",
"name": "Hue color spot 1",
"modelid": "LCG002",
"manufacturername": "Signify Netherlands B.V.",
"swconfigid": "9FD98F72"
}
现在我想用Java将“on:true”修改为“on:false”。为此,我有以下代码:
URL url = new URL("http://192.168.0.53/api/HZ3bJqN3MIb35uNcI4FfsGcqstwbW6qgvuxd7Tmt/lights/1/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("PUT");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setConnectTimeout(60000);
connection.setReadTimeout(60000);
connection.setRequestProperty("Content-Type", "application/json");
JSONObject requestBody = new JSONObject();
requestBody.put("on", false);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(requestBody.toString());
writer.flush();
writer.close();
// Debug
int response = connection.getResponseCode();
System.out.println(requestBody.toString());
System.out.println(response);
这将返回'200'和{“on”:false},这将是完美的。
但出于某种原因,它什么也没做。即使存在连接,指示灯仍亮起
知道为什么吗?我也在尝试做同样的事情,但不知道Java部分 我让curl在命令级别使用三个引号:
curl -X PUT -H "Content-Type: application/json" -d {"""on""":false} http://192.168.0.53/api/HZ3bJqN3MIb35uNcI4FfsGcqstwbW6qgvuxd7Tmt/lights/1/state
此代码将与您的色调灯一起工作,请在您开始工作时与我共享Java代码。mike@toggle.is您对PUT请求使用了错误的URL 对
http://192.168.0.53/api/.../lights/1
将返回当前状态
但要修改,您需要向
http://192.168.0.53/api/.../lights/1/state
您所说的“它不发送”到底是什么意思?当您尝试通过命令行对其进行卷曲时(on:true和on:false),响应代码是什么?e、 g:curl-xput-d'{“on”:true}我在Windows Shell和GitBash(Linux)中执行了命令curl-xput-d'{“on”:false}'192.168.0.53/api/hz3bjqn3mib35unc4ffsgcqstwbw6qgvuxd7tmt/lights/1/state
。它在git bash中有效,但在cmd中无效。@tgdavies我编辑并试图更好地解释它。您需要另一个api(链接)进行编辑。