在Java中验证Http请求的方法?

时间:2018-08-28 11:26:45

标签: java apache http http-post

我正在尝试验证服务器中的HTTP请求。 http客户端可以向我发送不同的请求,其中有些请求可能与我的服务器不匹配,因此在这种情况下,我必须向客户端发送响应,表明请求有问题。

在继续阅读之前,请考虑更改字段名称的顺序不会影响响应。因此,字段的顺序无关紧要。

例如: 这是法律要求:

POST http://localhost HTTP/1.1
HOST: (here is an IP adress)
Content-Length: 50
Connection: Close
Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l
User_Id = 123456
Item_Id = 5007
Color = 1010

(注意:如果请求只有这些字段名称,则该请求将是合法的, 如果它包含任何其他字段名称,将被视为非法)

由于请求有效,因此我的服务器将发送200 OK作为响应,如下所示:

HTTP/1.1 200 OK
Connection: Close
Payment: 2755201

但是,例如,如果请求的字段或未知字段的值错误,则如下所示: 错误的User_Id值:

POST http://localhost HTTP/1.1
HOST: (here is an IP adress)
Content-Length: 50
Connection: Close
Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l
User_Id = -2323
Item_Id = 5007
Color = 1010

响应将是:

HTTP/1.1 200 OK
Connection: Close
Error_ID: 602
Error_String: Error in user_Id (illegal user ID)

或未知的字段名称:

POST http://localhost HTTP/1.1
HOST: (here is an IP adress)
Content-Length: 50
Connection: Close
Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l
User_Id = 123456
Item_Id = 5007
Sale = 0.5
Color = 1010

响应将是:

HTTP/1.1 200 OK
Connection: Close
Error_ID: 602
Error_String: Sale , unknown field name

作为一种验证方式,我考虑将所有有效字段名称放入枚举,当我收到请求时,将基于此枚举对它们进行分析,但是我有更多有效字段(不仅user_Id,item_Id和color),因此采用这种方式可能会花费很长时间并且效率很低,尤其是因为对字段的顺序并不重要。

这是我的服务器代码:

@Test
    public void main() throws IOException
    {
        serverSocket = new ServerSocket(80);
        Socket clnt = null;
        while (true)
        {
            clnt = serverSocket.accept();
            System.out.println("after accept in server");
            BufferedReader request = new BufferedReader(new InputStreamReader(clnt.getInputStream()));
            BufferedWriter response = new BufferedWriter(new OutputStreamWriter(clnt.getOutputStream()));

            String req = ".", strReq = "";
            try
            {
                req=request.readLine();
                while (!req.equals(""))
                {
                    System.out.println(req);
                    strReq += (req + "\n");
                    req=request.readLine();
                }
            }
            catch (Exception e)
            {
                // TODO: handle exception
                e.printStackTrace();
                System.out.println("xxxx");
            }
            System.out.println(strReq);
            String httpResponse = "HTTP/1.1 200 OK\r\n";
            //here will be the rest of the response
            response.write(httpResponse);
            System.out.println(httpResponse);
            response.flush();
        }
    }

我是http的新手,所以如果有一些验证库或任何其他更有效的验证方法,我会很感激。

1 个答案:

答案 0 :(得分:-1)

使用Spring mvc控制器。它使您的生活更轻松。验证将自动进行。例如

  @RequestMapping(value = "user", method = RequestMethod.POST) 
  public Response addUser(@RequestBody @Valid User user) {
    return userService.addUser(user);
  }

public class User implements Serializable {

private Long id;
@NotNull
@NotEmpty
private String userName;
@NotNull
@NotEmpty
private String password;
@NotNull
@NotEmpty
private String firstName;
private String lastName;

//all getters and setters here

}
@ControllerAdvice
@RestController
public class GlobalExceptionController {

 @ExceptionHandler({Exception.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public  Response handleBadRequest(Exception ex) {
    Response response = new Response();
    response.setStatus(HttpStatus.BAD_REQUEST.value());
    response.setMessage(ex.getMessage());
    return response;
}
}

所有验证都将通过注释@Valid进行。如果需要,可以在Spring全局异常控制器中处理异常