1

我正在编写 android 代码以使用新发布的 API 更改 Nest 恒温器中的字段。身份验证和获取字段值的工作非常完美,但是我在更改字段值时遇到了问题。基于用于更改您需要使用 HTTP put 的字段值的 API,但是一旦我这样做了,设备中什么也没有发生(值(例如 target_temperature_f 的值不会改变!))

这是我的安卓代码:

    String url = "https://developer-api.nest.com/devices/thermostats/" 
            + this.device_id + "?auth=" + this.access_token;    
    try{
        HttpClient httpclient = new DefaultHttpClient();

        /** set the proxy , not always needed  */
        HttpHost proxy = new HttpHost(proxy_ip,proxy_port);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);       

        // Set the new value
        HttpPut httpPut = new HttpPut(url);

        httpPut.setHeader("Content-Type", "application/json");

        JSONObject jsonObj = new JSONObject("{\"target_temperature_f\":'60'}");
        HttpEntity put_entity =  new StringEntity(jsonObj.toString());
        httpPut.setEntity(put_entity);

        HttpResponse put_response = httpclient.execute(httpPut);

我可以通过 linux 中的“curl”命令在设备中设置字段!!所以设备工作正常。

非常感谢任何帮助!

4

1 回答 1

2

我不确定如何使用DefaultHttpClient并且根据文档已弃用它以支持HttpURLConnection

下面是一些使用 HttpURLConnection 的代码,我用 Hue 灯测试过。

这将打开一个 URL 连接并使用给定的正文执行 POST 查询。readFromHttpConnection 方法需要一个 JSON 响应。看起来 Nest 使用 JSON,所以这可能会满足您的需求。

private String synchronousPostMethod(String destination, String body)
{
    Log.i(TAG, "Attempting HTTP POST method. Address=" + destination + "; Body=" + body);

    String responseReturn;

    try
    {
        HttpURLConnection httpConnection = openConnection(destination);
        httpConnection.setDoOutput(true);
        httpConnection.setRequestMethod("POST");

        writeToHttpConnection(httpConnection, body);

        responseReturn = readFromHttpConnection(httpConnection);
    }
    catch(Exception e)
    {
        responseReturn = RESPONSE_FAIL_MESSAGE + "; exception = " + e;
    }

    Log.i(TAG, "Result of HTTP POST method: " + responseReturn);

    return responseReturn;
}

这些是辅助方法。

private HttpURLConnection openConnection(String destination)
{
    HttpURLConnection httpConnection = null;

    try
    {
        URL connectionUrl = new URL(destination);
        httpConnection = (HttpURLConnection) connectionUrl.openConnection();
    }
    catch(MalformedURLException malformedUrlException)
    {
        Log.w(TAG, "Failed to generate URL from malformed destination: " + destination);
        Log.w(TAG, "MalformedURLException = " + malformedUrlException);
    }
    catch(IOException ioException)
    {
        Log.w(TAG, "Could not open HTTP connection. IOException = " + ioException);
    }

    return httpConnection;
}

private boolean writeToHttpConnection(HttpURLConnection httpConnection, String data)
{
    // No data can be written if there is no connection or data
    if(httpConnection == null || data == null)
    {
        return false;
    }

    try
    {
        OutputStreamWriter outputStream = new OutputStreamWriter(httpConnection.getOutputStream());
        outputStream.write(data);
        outputStream.close();
    }
    catch(IOException ioException)
    {
        Log.w(TAG, "Failed to get output stream from HttpUrlConnection. IOException = " + ioException);

        return false;
    }

    return true;
}

private String readFromHttpConnection(HttpURLConnection httpConnection)
{
    String responseReturn = "";

    if(httpConnection != null)
    {
        try
        {
            InputStream response = httpConnection.getInputStream();
            int size;

            do
            {
                byte[] buffer = new byte[mResponseBufferSize];
                size = response.read(buffer, 0, mResponseBufferSize);

                // Convert the response to a string then add it to the end of the buffer
                responseReturn += new String(buffer, 0, size);
            }while(size < mResponseBufferSize || size <= 0);

            // Cleanup
            response.close();
        }
        catch (IOException ioException)
        {
            Log.w(TAG, "Failed to get input stream from HttpUrlConnection. IOException = " + ioException);
        }
    }

    return responseReturn;
}
于 2014-08-02T01:00:34.017 回答