当内容类型为application / x-www-form-urlencoded时,Java读取POST数据

问题描述 投票:4回答:2

我有一个正在测试的API。该API接收POST请求并按如下方式读取它

      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*/ }

当我在“ application / json; charset = utf-8”中发送POST请求时,一切正常。

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

它打印此:

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

而且我可以正确读取数据。

但是我的问题是,当我以相同的方式发送数据但我将内容类型设置为“ application / x-www-form-urlencoded; charset = utf-8”时

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

测试是相同的,只是内容类型不同,但是似乎我不再收到任何数据了:

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

任何想法?

///更新

这里是弹簧控制器

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

//更新2这是我发送数据的方式

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

我知道创建Json并以“ application / x-www-form-urlencoded”发送它并没有多大意义,但这只是我们的一个用户无法解决他的问题,它只会发送“ application / x-www-form-urlencoded“。

java spring-mvc post mime-types content-type
2个回答
0
投票

[使用Spring时,request.getReader()不适用于读取application/x-www-form-urlencoded数据。相反,此数据可用作参数,因此您可以使用:

读取它
@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));
    }
}

例如,您可以使用curl进行测试:

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

将打印

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

或者,如果您事先知道可能的参数,则可以使用类似以下的内容:

@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);
}

-1
投票

@ RequestMapping的'produces'属性显示客户端只能接受application / json数据,因此您可以将其删除或将其更改为'application / x-www-form-urlencoded'。

© www.soinside.com 2019 - 2024. All rights reserved.