提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
使用httpclient实现两个服务之间传递信息
案例:
A服务传入参数调用B服务的登入接口
一、引入Maven依赖
<!-- https://mvnrepository.com/artifact/com.seepine/httpclient -->
<dependency>
<groupId>com.seepine</groupId>
<artifactId>httpclient</artifactId>
<version>1.0.0</version>
</dependency>
二、使用步骤
1.服务器A控制层
代码如下(示例):
@RestController
@Slf4j
@RequestMapping("/file")
public class CommonController {
@PostMapping("/test")
public String postTest(@RequestBody User user, HttpServletRequest request){
//创建map集合 调用B服务传入的参数
Map<String,String > map=new HashMap<>();
//将传入的对象转换成Json形式的数据
String userJson = JSON.toJSONString(user);
//传入map集合
map.put("res", userJson);
//httpUtil会根据 url中的header 自动判断请求方式等,确保请求方式一致
String result = HttpUtil.sendPost("http://localhost:8082/user//login", map);
return result;
}
注意:
最好先将数据转换成Json形式的数据在进行传递否则服务器B接受后会出现BUG没办法转换成对象的对象或者集合。
2.服务器B控制层
@Controller
@Slf4j
@RequestMapping("/user")
public class User1Controller {
@Autowired
UserService userService;
/**
* 用户登入
* @param
* @return
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public User login(@RequestBody String res) throws UnsupportedEncodingException {
//服务A传过来的参数,有可能是乱码,需要先设置一下编码格式
String decode = URLDecoder.decode(res, "UTF-8");
log.info("账户:{}",decode);
//将Map中 的Key截取 只留下value的值
String result = decode.substring(4);
//将value中的jason数据转换成java对象
User user = JSON.parseObject(reslut, User.class);
return user;
}
注意:
通过httpclient 进行服务器互相调用的时候,被调用的服务器接受数据时,只能是String 类型
接受后在进行 JSON和JAVA的转换