项目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;
}
}