本文共 3533 字,大约阅读时间需要 11 分钟。
首先:
引入工具类: 可以自行添加/修改public class Constants { public static final String TEST = "http://127.0.0.1:8080"; public static final String PRODUCT_MANAGEMENT_HOST = "http://127.0.0.1:8090";}
引入HttpClient支持:
@Autowiredprivate RestTemplate restTemplate;
1.查询数据 :getForEntity(url,Object.class)
参数一: 需要调用服务的地址(可以携带数据) 参数二:String.class表示我希望返回的body类型是String 返回值类型: ResponseEntity*<*T*>* 或 ResponseEntity*<*T*>*
@GetMapping("/findProductByPage") public ResponseEntityfindProductByPage(Integer page, Integer rows,Product product){ HttpStatus statusCode = null; try { String url = Constants.PRODUCT_MANAGEMENT_HOST+ "/product/findProductByPage?page="+page+"&rows="+rows+"&product="+product; ResponseEntity entity = restTemplate.getForEntity(url, String.class);//跨服务器访问 statusCode = entity.getStatusCode();//获取状态码 String body = entity.getBody(); //获取返回数据 return new ResponseEntity<>(body,statusCode); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(statusCode); } }
2.保存数据: postForEntity(url,pojo,Object.class)
参数一:同上 参数二:传递的数据 参数三:同上*注意:该方法传递给跨服务器是 方法参数上需要加上@RequestBody 否则无法接受到数据@PostMapping("/saveProduct") public ResponseEntitysaveProduct(Product product){ HttpStatus statusCode =null; try { JSONObject proJson = JSONObject.fromObject(product); String prodct = proJson.toString(); String url = Constants.PRODUCT_MANAGEMENT_HOST+"/product/saveProduct"; ResponseEntity entity = restTemplate.postForEntity(url, prodct, String.class); String body = entity.getBody(); statusCode = entity.getStatusCode(); return new ResponseEntity<>(HttpStatus.CREATED); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(statusCode); } }
//全部类:我使用的--->勿喷
@RestController@RequestMapping("/product")public class ProductController { @Autowired private RestTemplate restTemplate; @GetMapping("/findProductByPage") public ResponseEntityfindProductByPage(Integer page, Integer rows,Product product){ HttpStatus statusCode = null; try { String url = Constants.PRODUCT_MANAGEMENT_HOST+ "/product/findProductByPage?page="+page+"&rows="+rows+"&product="+product; ResponseEntity entity = restTemplate.getForEntity(url, String.class); statusCode = entity.getStatusCode();//获取状态码 String body = entity.getBody(); //获取返回数据 return new ResponseEntity<>(body,statusCode); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(statusCode); } } @PostMapping("/saveProduct") public ResponseEntity saveProduct(Product product){ HttpStatus statusCode =null; try { JSONObject proJson = JSONObject.fromObject(product); String prodct = proJson.toString(); String url = Constants.PRODUCT_MANAGEMENT_HOST+"/product/saveProduct"; ResponseEntity entity = restTemplate.postForEntity(url, prodct, String.class); String body = entity.getBody(); statusCode = entity.getStatusCode(); return new ResponseEntity<>(HttpStatus.CREATED); } catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(statusCode); } }}
转载地址:http://yprxx.baihongyu.com/