javascript - 如何发送参数来发布http请求?

标签 javascript java http xmlhttprequest http-post

我有一个 javaScript 代码,我在其中发送带有一些参数的 http 帖子。 Post 参数是一个 json,如下所示: {"tokenRequest":{"authSpecification":{"authToken":"T7SUNv0j2eRTeu04tVbcSa0LHN1YnNjcmliZXItMTk2LDEsRk9YVEVMLDE5NiwxMT"},"contentSpecification":{"contentId":"abc"}}}

在 JavaScript 中,我只是简单地打开请求、设置 header 和发送参数。发布请求如下所示:

var request = new XMLHttpRequest();
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
request.send(tokenRequestJSON); //tokenRequestJSON is the json parameter mentioned above

现在我需要在 Java 中进行相同的调用(由于某些内部 POC 要求)。为此,我做了以下事情:

AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
Map<String,String> httpHeaders = new HashMap<>();
httpHeaders.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
for (Map.Entry header : httpHeaders.entrySet()) {
                asyncHttpClient.addHeader((String)header.getKey(), (String)header.getValue());
            }
RequestParams postData1 = new RequestParams();
String tokenRequest1 = "{\"tokenRequest\":{\"authSpecification\":{\"authToken\":\"T7SUNv0j2eRTeu04tVbcSa0LHN1YnNjcmliZXItMTk2LDEsRk9YVEVMLDE5NiwxMT\"},\"contentSpecification\":{\"contentId\":\"abc\"}}}";
postData1.put("arg0", tokenRequest1);
asyncHttpClient.post(url, postData1, new ResponseHandler());

但它给我错误。 {"errorResponse": {"status": "ERROR", "errorCode": "MDRM-0002", "errorMessage": "Json body not properly formed (No JSON object could be decoded)"}}

我是 Java 的新手,我可能缺少一些基本的东西。您知道为什么来自 java 的请求会失败吗?

提前致谢。

最佳答案

你在使用 AsyncHttpClient

RequestParams postData1 = new RequestParams();
postData1.put("arg0", tokenRequest1) // this is not a json object, not the body of the request.

请求参数是url上的参数,例如“date”是一个请求参数: http://localhost:8080/MyApp/user/1234/invoices?date=12-05-2013

关于javascript - 如何发送参数来发布http请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51667309/

相关文章:

javascript - 如何等待来自 Redux 操作创建者的多个 API 调用?

javascript - 使用 Froala 编辑器按空格键时 Sweet alert 2 关闭

javascript - 在 Chrome 中动态添加 <hr> 显示问题

java - 如何让 Maven 在打包时将属性写入属性文件?

java - 如何发送屏幕查看事件,以帮助Firebase预测做出更准确的预测

java - NetBeans 在每个添加的框架中插入 main() 方法

http - OpenID Connect 访问 token 有什么用?

.htaccess - 从 http 重定向到 https 是否有加密

http - svnedge 中的非法 cookie 属性

javascript - 使 Javascript 动画继续而不重置