通过Java的Rest API发送Http POST请求 [英] Sending Http POST Request through Rest API in Javascript

查看:118
本文介绍了通过Java的Rest API发送Http POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Rest API密钥将Http发布请求发送到parse.com服务器.不知道我是否按照下面的方法正确进行操作.以下是我的整个脚本,并创建了一个按钮,该按钮应在简单的HTML页面中触发发布请求.

I am trying to send an Http post request to parse.com server through Rest API keys. Not sure if I am doing it right as below. The following is my whole script and makes a button which should trigger the post request in a simple HTML page.

<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />
<script>

xmlhttp = new XMLHttpRequest();
var url = "https://api.parse.com/1/classes/english";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.setRequestHeader("X-Parse-Application-Id", "VnxVYV8ndyp6hE7FlPxBdXdhxTCmxX1111111");
xmlhttp.setRequestHeader("X-Parse-REST-API-Key","6QzJ0FRSPIhXbEziFFPs7JvH1l11111111");
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        alert(xmlhttp.responseText);
    }
}
var parameters = {
    "ephrase": "english",
    "pphrase": "farsi",
     "nvote": 0,
    "yvote": 0
};
// Neither was accepted when I set with parameters="username=myname"+"&password=mypass" as the server may not accept that

function doFunction() {
  xmlhttp.send(parameters);
}

</script>

推荐答案

xmlhttp.send(parameters);
             ^^^^^^^^^^

这需要是一个字符串,但它是一个对象,因此将被转换为字符串:"[object Object]".

That needs to be a string, but it is an object, so will be converted to the string: "[object Object]".

您需要先将数据转换为正确的编码.

You need to convert the data to the proper encoding first.

您已经说过:

xmlhttp.setRequestHeader("Content-type", "application/json");

因此您可以使用JSON.stringify(parameters).

这篇关于通过Java的Rest API发送Http POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆