【问题标题】:Trouble with setting the Nest field values via java/android code通过 java/android 代码设置 Nest 字段值的问题
【发布时间】:2014-08-01 22:54:54
【问题描述】:

我正在编写 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”命令在设备中设置字段!!所以设备工作正常。

非常感谢任何帮助!

【问题讨论】:

    标签: android curl nest-api


    【解决方案1】:

    我不确定如何使用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;
    }
    

    【讨论】:

    • 托尼,非常感谢。我意识到问题是由于“重定向”造成的。现在已处理,因此我的代码会跟踪重定向的 url。问题解决了!不过感谢您的评论。
    猜你喜欢
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 2011-05-01
    • 2016-04-09
    • 2014-09-17
    • 1970-01-01
    相关资源
    最近更新 更多