如何在$ http POST方法

时间:2017-01-11 12:38:01

标签: java spring http post

如何在$ http post方法中隐藏params。如果我使用数据而不是给定示例中的params,我已经将近400个服务器端请求getter从request.getParameter(“key”)更改为request.getReader(); 我有一个情况。我们即将从request.getParameter迁移到request.getReader。 原因:从requet URL中删除表单参数。

来自:http://localhost:8080/myApp/test.do?test1=abc&test2=def

http://localhost:8080/myApp/test.do

这是我所取得的成就。 样品申请(旧):

            $scope.myJson = {
        'abc' : '123',
        'def' : '456',
    };

    $http({

        method : 'POST',
        url : 'test.do',
        param : {
            'test1' : $scope.myJson,
        },
        headers : {
            'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    }). success(function(data, status, headers, config) {


    }).
    error(function(data, status, headers, config) {
    });

示例请求新

            $scope.myJson = {
        'abc' : '123',
        'def' : '456',
    };

    $http({

        method : 'POST',
        url : 'test.do',
        data: {
            'test1' : $scope.myJson,
        },
        headers : {
            'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    }). success(function(data, status, headers, config) {


    }).
    error(function(data, status, headers, config) {
    });

正如您所见,我已将参数更改为数据。

服务器端(旧);

final String myJson= request.getParameter("test1");

服务器端(新):

     StringBuffer jb = new StringBuffer();
      String line = null;
      try {
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null)
          jb.append(line);
      } catch (Exception e) {
          e.printStackTrace();/*report an error*/ }

      try {
        JSONObject jsonObj = new JSONObject(jb.toString());
        JSONObject jsonObj1 =jsonObj.getJSONObject("test1");
        String test1= jsonObj1.toString();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   

这是处理这个场景的方式吗?我们在应用程序中有大约400多项服务。任何快速解决方法?

编辑1:

public class myController extends AjaxBaseController {


    @Override
    public ModelAndView executeAjaxCall(final HttpServletRequest request, final HttpServletResponse response) {


        final String test1= request.getParameter("test1");               

        final InputParam loginParam = JsonUtil.convertPojo(test1,InputParam .class); // POJO class
//other logics 

    };
}

3 个答案:

答案 0 :(得分:2)

我认为改变你的控制器没有任何(好的)方法(为什么你要手工处理参数,这就是Spring的用途)。

在Spring中,params被解析为单独的方法参数@RequestParam,如下所示:

public String doWork(@RequestParam("name") String value, .......)

您希望更改此设置,以便后端接收JSON数据,即使用@RequestBody支持的HttpMessageConverter来处理Spring,该Context-Type是基于发布的public String doWork(@RequestBody MyDto object) 标头选择的。看起来像这样

public String doRequest(@RequestBody Map<String, String> map) {
   String abc = map.get("abc");
   String def = map.get("def");
}

我非常了解Spring网络堆栈,我可能会找到解决方法,但这是一个糟糕的主意,并且只会在将来给你带来问题(当有人希望从JSON发布一个列表时) ),我甚至不会尝试提出解决方案。

如果您有400个控制器方法,可能会使转换速度更快,因此要跳过DTO步骤并使用像这样的地图

$table->integer('some_field')->unsigned()->nullable();

答案 1 :(得分:1)

首先,你正在做的这个“隐藏”不会让你的API更安全。如果有人可以看到HTTP请求,那么查看正文中发送的params与请求URL中发送的params相比并不困难。

(如果你想隐藏第三方的参数,请使用HTTPS。如果你想将它们隐藏起来......对不起,但这是不可能的。)

假设您正在做的事情是值得的,并且您希望保持重新编码工作量将服务器端更改为最小,那么我建议您设计一个实用程序/帮助程序方法,它相当于您的“新”服务器端代码。这是一个起点...

public JSONObject getRequestParams(Request request) {
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            jb.append(line);
        }
    } catch (IOException e) {
        /*report / handle error*/ 
    }

    try {
        return = new JSONObject(jb.toString());
    } catch (JSONException e) {
        /* report / handle error */
    }   
}

然后您的特定示例可以编码为:

final JSONObject myJson = 
       getRequestParams(request).getJSONObject("test1");

根据您需要处理的参数范围,您可以使用不同的辅助方法来获取单个参数,多个参数,处理“可选”和“强制”参数,生成一致的状态代码和响应的错误报告等等。

一般原则是检查400个左右的REST API调用的代表性示例,并花时间设计辅助方法,以便您可以简洁有效地提取参数。

UPDATE - 我没注意到这是一个Spring MVC项目。这大大改变了。如果您使用Spring MVC的请求映射基础结构(正确),那将透明地处理URL和正文中传递的参数;见Klaus Groenbaek的回答。

答案 2 :(得分:0)

您必须将queryParameters更改为FormParam

相关问题