当前位置: 首页 > 知识库问答 >
问题:

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

傅浩漫
2023-03-14

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

你知道吗?

///更新

这里是Spring控制器

@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);
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", "johnsmith42@yopmail.com");
        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

共有1个答案

韦高阳
2023-03-14

使用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);
}
 类似资料: