7
votes

I have an API that I'm testing. The API receives POST requests and reads it like this

      StringBuffer jb = new StringBuffer();
      String line = null;
      try {
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null)
            jb.append(line);

        System.out.println("jb: "+jb);
        System.out.println("request.getHeader('content-type'): "+request.getHeader("content-type"));

      } catch (Exception e) { /*report an error*/ }

All works fine when I send a POST request in "application/json;charset=utf-8"

httpPost.setHeader("content-type", "application/json;charset=utf-8");

It prints this:

jb: {"client_domain":"=....); //proper Json data
request.getHeader('content-type'): application/json;charset=utf-8

And I can read the data properly.

However my problem is when I send the data the same way but I set the content-type "application/x-www-form-urlencoded;charset=utf-8"

httpPost.setHeader("content-type", "application/x-www-form-urlencoded;charset=utf-8");

The test is the same just the content-type is different but then it seems that I don't receive any data anymore:

jb: 
request.getHeader('content-type'): application/x-www-form-urlencoded;charset=utf-8

Any idea?

/// Update

Here is the Spring Controller

@RequestMapping(value = {"user/add"}, method = RequestMethod.POST, produces="application/json; charset=utf-8")
@ResponseBody
public ResponseEntity<String> getNewUserApi(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    Map<String, Object> jsonObj = new HashMap<String, Object>();

    StringBuffer jb = new StringBuffer();
      String line = null;
      try {
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null)
            jb.append(line);

        System.out.println("jb: "+jb);
        System.out.println("request.getHeader('content-type'): "+request.getHeader("content-type"));

      } catch (Exception e) { /*report an error*/ }
    ///I create my JSon that will be sent back
    return JsonUtils.createJson(jsonObj);

//UPDATE 2 Here is how I send the data

public static void main(String[] args) throws Exception {

    String url = "http://localhost:8080/child/apiv1/user/add";
    CloseableHttpClient client = HttpClientBuilder.create().build();

    HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader("content-type", "application/x-www-form-urlencoded;charset=utf-8");

    try {
        //we had to the parameters to the post request
        JSONObject json = new JSONObject();

        json.put("client_id", "fashfksajfhjsakfaskljhflakj");
        json.put("client_secret", "9435798243750923470925709348509275092");
        json.put("client_domain", "dummy.localhost.com");

        //create the user json object
        JSONObject userObj = new JSONObject();
        userObj.put("email", "[email protected]");
        userObj.put("name", "Anna Sax");

        JSONArray childrenArray = new JSONArray();

        JSONObject child1 = new JSONObject();
        child1.put("name", "Iphone 6");
        child1.put("age", "2");
        childrenArray.put(child1);
        userObj.put("children", childrenArray);
        json.put("user", childObj);

        StringEntity params = new StringEntity(json.toString());
        httpPost.setEntity(params);

        System.out.println("executing request: " + httpPost.getRequestLine());
        HttpResponse response;
        response = client.execute(httpPost);

   //[...]       

} //End main

I know it doesn't really make sense to create Json and send it in "application/x-www-form-urlencoded" but it's just that one of our users can't fix his issue and it will only send "application/x-www-form-urlencoded".

2
Do you have code for controller(or equivalent to controller) class?. if so, please post it.Rehman
How do you send data for content-type application/x-www-form-urlencoded;charset=utf-8? The must be in key value pairs with a = sign and multiple key values must be appended with ? like client_domain=122.0.0.1 etcshazin
@Rehman I posted the controller. Shazin Yes it should be like that but I just don't get the data.drimk
Can you add how you send the URL encoded data?Soana
@Soana I added the way it is sent.drimk

2 Answers

0
votes

When using Spring, request.getReader() will not work for reading application/x-www-form-urlencoded data. Instead this data is available as parameters, so you can read it with:

@PostMapping(path = "/mypostendpoint", consumes = "application/x-www-form-urlencoded")
public void handleFormData(HttpServletRequest request) {
    Enumeration<String> params = request.getParameterNames();
    while (params.hasMoreElements()) {
        String param = params.nextElement();
        System.out.println("name = " + param + ", value = " + request.getParameter(param));
    }
}

You can test this with curl for example:

curl -X POST http://localhost:8080/mypostendpoint -d 'myparam1=X' -d 'myparam2=Y'

will print

name = myparam1, value = X
name = myparam2, value = Y

Alternatively, if you know the possible parameters in advance you can use something like this:

@PostMapping(path = "/mypostendpoint", consumes = "application/x-www-form-urlencoded")
public void handleMyPost(@RequestParam("myparam1") String value1,
                         @RequestParam("myparam2") String value2) {
    System.out.println("value of myparam1 = " + value1);
    System.out.println("value of myparam2 = " + value2);
}
-2
votes

The 'produces' attribute of @RequestMapping shows that the client could only accept application/json data, so you can remove it or change it into 'application/x-www-form-urlencoded'.