SpringBoot调用其他服务接口的方法

第一种方法

@RequestMapping("/doPostGetJson")
public String doPostGetJson() throws ParseException {
//此处将要发送的数据转换为json格式字符串
String jsonText = “{id:1}”;
JSONObject json = (JSONObject) JSONObject.parse(jsonText);
JSONObject sr = this.doPost(json);
System.out.println(“返回参数:” + sr);
return sr.toString();
}

public static JSONObject doPost(JSONObject date) {
HttpClient client = HttpClients.createDefault();
// 要调用的接口方法
String url = “http://192.168.1.101:8080/getJson”;
HttpPost post = new HttpPost(url);
JSONObject jsonObject = null;
try {
StringEntity s = new StringEntity(date.toString());
s.setContentEncoding(“UTF-8”);
s.setContentType(“application/json”);
post.setEntity(s);
post.addHeader(“content-type”, “text/xml”);
HttpResponse res = client.execute(post);
String response1 = EntityUtils.toString(res.getEntity());
System.out.println(response1);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
jsonObject = JSONObject.parseObject(result);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return jsonObject;
}

第二种方法(推荐)

@FeignClient(value = “sd-authority” url = “${xx.xxx.xx}”)
public interface Afegin{
@requestMapping("/insert")
public void function1(String name);
}
@EnableFegnClients(basePackages = {“xx.x.xx.x.xx”})
public class DataSourceProjectConfig{}

备注:url里面配置的是yaml文件里面,调用其他服务的路径,Afegin接口对应的是要调用的服务的接口,参数和返回值保持一致,即接口原封不动的粘贴过来;比如其他服务的controller里面的A方法如下:
@GetRequestMapping("/")
public Result A(@requestBody Params params){
A方法的逻辑
}
Afegin接口里面对应的是:
@GetRequestMapping("/")
public Result A(@requestBody Params params);
basePackages里面是接口放置的位置,到包一层就可以,不用对应到文件上,所以,其他服务,远程调用的接口放在同一个包下面

你可能感兴趣的:(SpringBoot)