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

时间:2015-10-28 06:23:55

标签: java post mime-types content-type

我有一个我正在测试的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 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);

//更新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", "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

我知道创建一个Json并将其发送到&#34; application / x-www-form-urlencoded&#34;并不是真的有意义。但它只是我们的一个用户无法解决他的问题,它只会发送&#34; application / x-www-form-urlencoded&#34;。

2 个答案:

答案 0 :(得分:0)

&#39;生产&#39; @RequestMapping的属性显示客户端只能接受应用程序/ json数据,因此您可以删除它或将其更改为&#39; application / x-www-form-urlencoded&#39;。

答案 1 :(得分: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);
}