我有一个 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/