Search code examples
javascriptjavahttpxmlhttprequesthttp-post

How to send param to post http request?


I have a javaScript code where i am sending http post with some parameters. Post parameter is a json that looks like this: {"tokenRequest":{"authSpecification":{"authToken":"T7SUNv0j2eRTeu04tVbcSa0LHN1YnNjcmliZXItMTk2LDEsRk9YVEVMLDE5NiwxMT"},"contentSpecification":{"contentId":"abc"}}}

In JavaScript, I simply open request, set headers and send parameters. Post request looks like:

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

Now I need to make same call in Java (due to some internal POC requirement). For that I did following:

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

But it is giving me error. {"errorResponse": {"status": "ERROR", "errorCode": "MDRM-0002", "errorMessage": "Json body not properly formed (No JSON object could be decoded)"}}

I am new to Java, I may be missing some basic stuff. Do you know, why request from java is failing?

Thanks in advance.


Solution

  • Are you using AsyncHttpClient ?

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

    Request param is param on the url, for example, "date" is a request param: http://localhost:8080/MyApp/user/1234/invoices?date=12-05-2013