简体   繁体   English

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

[英]How to send a PUT request with payload using POST or GET?

I need to send a PUT request with a payload to an API (Philips Hue Bridge), but I have some limitations in javascript.我需要将带有负载的 PUT 请求发送到 API(Philips Hue Bridge),但我在 javascript 中有一些限制。 I can only use:只能使用:

XMLHttpRequest methods: XMLHttpRequest 方法:

open(method, url [, async = true [, username = null [, password = null]]])
Sets the request method, request URL, and synchronous flag.设置请求方法、请求 URL 和同步标志。 Supported request method : GET, POST支持的请求方式:GET、POST

send(data = null)
Initiates the request.发起请求。 The optional 'data' argument allows only UTF-8 encoded string type.可选的 'data' 参数只允许使用 UTF-8 编码的字符串类型。 The argument is ignored if request method is GET.如果请求方法为 GET,则忽略该参数。

abort()
Cancels any network activity.取消任何网络活动。

This limitation comes from the Tizen Wearable Web Widget Specification此限制来自Tizen Wearable Web Widget 规范


Philips Hue Bridge API expects:飞利浦 Hue Bridge API 期望:

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

Method: PUT方法: PUT

Payload example: {"on": true}负载示例: {"on": true}


What I tried:我试过的:

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

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

Also tried GET and POST with following URL endings:还尝试使用以下 URL 结尾的GETPOST
../state?{on=true}
../state?{on:true}
../state?{"on"=true}
../state?{"on":true}
Response: 400 (Bad request)响应: 400 (Bad request)

Again, I cannot use any additional libraries or commands besides the XMLHttpRequest methods mentioned above.同样,除了上面提到的 XMLHttpRequest 方法之外,我不能使用任何其他库或命令。

How can I solve this?我该如何解决这个问题?

below is the sample code.下面是示例代码。 you can try this way in your code.您可以在代码中尝试这种方式。

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);

Changing the method property to PUT should do the trick.method属性更改为PUT应该可以解决问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM