如何使用POST或GET发送带有有效负载的PUT请求?

时间:2020-01-10 13:22:12

标签: javascript tizen-web-app philips-hue

我需要将带有有效负载的PUT请求发送到API(Philips Hue Bridge),但是我在javascript中有一些限制。 我可以使用:

XMLHttpRequest方法:

open(method, url [, async = true [, username = null [, password = null]]])
设置请求方法,请求URL和同步标志。 支持的请求方法:GET,POST

send(data = null)
发起请求。可选的“ data”参数仅允许使用UTF-8编码的字符串类型。如果请求方法是GET,则忽略该参数。

abort()
取消任何网络活动。

此限制来自Tizen Wearable Web Widget Specification


Philips Hue Bridge API预期:

URL: http://hostname/api/username/lights/lightKey/state

方法: PUT

有效负载示例: {"on": true}


我尝试过的事情:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://hostname/api/username/lights/lightLey/state?on=true');
xhr.send();
响应: 400 (Bad request)

var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://hostname/api/username/lights/lightLey/state?on=true');
xhr.send();
响应: 400 (Bad request)

还尝试了GETPOST使用以下URL结尾:
../state?{on=true}
../state?{on:true}
../state?{"on"=true}
../state?{"on":true}
响应: 400 (Bad request)

同样,除了上面提到的XMLHttpRequest方法之外,我不能再使用任何其他库或命令。

我该如何解决?

2 个答案:

答案 0 :(得分:1)

下面的

是示例代码。您可以在代码中尝试这种方式。

var http = new XMLHttpRequest();
var url = 'your_URL.php';
var params = 'on=true';
http.open('PUT', url, true);

//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);

答案 1 :(得分:0)

method属性更改为PUT应该可以解决问题。

var xhr = new XMLHttpRequest();
xhr.open('PUT', 'http://hostname/api/username/lights/lightLey/state?on=true');
xhr.send();