如何在java中发送正确的httpput请求

ws51t4hk  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(283)

我想用philipshueapi用java关掉我的灯。为此,我有以下api:http://192.168.0.53/api/hz3bjqn3mib35unci4ffsgcqstwbw6qgvuxd7tmt/lights/1/
这将返回:

{
  "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},这将是完美的。但出于某种原因,它什么也没做。即使存在连接,灯仍亮。
知道为什么吗?

mzsu5hc0

mzsu5hc01#

您对put请求使用了错误的url。
get请求 http://192.168.0.53/api/.../lights/1 将返回当前状态
但要修改,您需要一个put请求 http://192.168.0.53/api/.../lights/1/state

zpjtge22

zpjtge222#

我也在尝试做同样的事情,但不知道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

相关问题