HttpClient进行服务器传递信息,HttpUtil工具类

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

使用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的转换

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值