springboot项目之间接口的相互调用 - Go语言中文社区

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;
    }
}
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_42799440/article/details/98480830
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢