HttpEntity的使用?
作者:互联网
1.简单介绍:
HttpEntity表示Http请求的实体和Http响应的实体;
RequestEntity表示请求的实体,里面有获取请求头,请求行,等内容的方法;
ResponseEntity表示Http响应的实体,里面有响应行,响应体等的方法;
HttpHeaders表示请求实体,响应实体的header头,通过创建httpHeaders放在requestEntity返回响应头的信息。
2.应用场景:
通常结合RestTemplate发送http请求,获取请求实体requestEntity,响应实体里面responseBody里面的数据。
3.举例说明:
3.1使用ajax发送异步请求
$.ajax({ type: "POST", url: targetUrl, data: user,//传递的参数 dataType:"json",//前端可以接收服务器传过来的数据的类型,json contentType: "application/json", beforeSend: function(xhr){//请求发送之前执行函数,添加请求头 xhr.setRequestHeader("token","shfashfdasfhdashfoasf"); }, success: function(user){ alert(user.username); }, error:function(){ alert("异常,请检查"); }
3.2controller接受请求过来的参数信息
1 @PostMapping("user/{id}") 2 public ResponseEntity<User>getUserId(@PathVariable("id")Long id, RequestEntity requestEntity){ 3 //获取请求url 4 System.out.println ("请求url:"+requestEntity.getUrl () ); 5 System.out.println ("获取请求头信息:" ); 6 HttpHeaders headers = requestEntity.getHeaders ( ); 7 8 System.out.println ("内容的长度:"+headers.getContentLength () ); 9 System.out.println ( "文档类型:"+headers.getContentType () ); 10 System.out.println ("accept:"+ headers.getAccept ()); 11 System.out.println ("Origin:"+ headers.getOrigin ()); 12 System.out.println ("TOKEN"+ headers.getFirst ("token")); 13 14 HttpHeaders responseHeader = new HttpHeaders ( ); 15 responseHeader.set ("key","value"); 16 User user = new User (); 17 user.setId (1L); 18 user.setName ("王杰"); 19 user.setAge (23); 20 user.setEmail ("yahuimiao"); 21 22 return new ResponseEntity<User> (user,responseHeader, HttpStatus.OK); 23 24 // User user = userService.findById (id); 25 // return user.toString (); 26 27 }
标签:HttpEntity,请求,System,headers,user,使用,println,out 来源: https://www.cnblogs.com/wangjie-logs/p/15088713.html