【问题标题】:How to send param to post http request?如何发送参数来发布 http 请求?
【发布时间】:2018-08-03 07:22:54
【问题描述】:

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

在 JavaScript 中,我只需打开请求、设置标头和发送参数。发布请求如下所示:

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 的请求失败了吗?

提前致谢。

【问题讨论】:

    标签: javascript java http xmlhttprequest http-post


    【解决方案1】:

    你在用AsyncHttpClient吗?

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

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

    【讨论】:

    • 是的,我正在使用 AyncHttpClient。那么我应该如何在Java中将参数发送到http post?
    • 这里有很多例子:stackoverflow.com/questions/7181534/…
    • 谢谢伙计。你是对的,我在 RequestParams 中传递了 JSON,这是错误的。现在我将 StringEntity 用于 JSON 并且它有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 2014-08-17
    相关资源
    最近更新 更多