springboot项目之间接口的相互调用

项目A调用项目B中的接口

步骤一:在项目A中书写Http的工具类:

package com.ideal.util;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import java.io.IOException;
public class HttpUtil {
        public static String doPost2(String url, JSONObject param) {
            HttpPost httpPost = null;
            String result = null;
            try {
                HttpClient client = new DefaultHttpClient();
                httpPost = new HttpPost(url);
                if (param != null) {
                    StringEntity se = new StringEntity(param.toString(), "utf-8");
                    httpPost.setEntity(se); // post方法中,加入json数据
                    httpPost.setHeader("Content-Type", "application/json");
                }
                HttpResponse response = client.execute(httpPost);
                if (response != null) {
                    HttpEntity resEntity = response.getEntity();
                    if (resEntity != null) {
                        result = EntityUtils.toString(resEntity, "utf-8");
                    }
                }
                } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
       return result;
        }
    }

步骤2:在application.yml中书写要调用的接口的目标路径(ip+端口+目录结构)
要调用的接口的路径
步骤三:在controller层通过@Value注解引入配置文件中的接口路径,通过工具类调用接口

@RestController
@RequestMapping("/user")
public class UserController {
@Value("${application.findUser}")
private String url;
    @Autowired
    private UserService userService;
    @PostMapping("/add")
    public void addUser(@RequestBody User user){
         JSONObject jsonObject=new JSONObject();
        jsonObject.put("userId",user.getUserId());
        jsonObject.put("userName",user.getUserName());
        jsonObject.put("passWord",user.getPassWord());
        HttpUtil.doPost2(url,jsonObject);
        System.out.println(jsonObject);
      userService.addUser(user);
    }
}

步骤4:B项目中的controller:

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
  @PostMapping("/find")
     public User findUser(@RequestBody User user){
    User user1 = userService.queryOne(user);
         System.out.println(user1);
    return user1;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值