在项目里只写controller和service,接口调用别人的大概流程,做个小笔记,controller层调service,service调接口
在service层开始吧
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("key", value);
//把map转成json字符串
String jsonObject = JSONObject.toJSONString(paramMap);
//获取接口URL
String url = SystemConfig.getinterface();
//远程接口调用
PerfectApplyResult vo = callPcUrl(url, jsonObject);
systemconfig里面是
static Properties sysConfigProp = new Properties();
static {
String sysConfigPath = "sysconfig.properties";
try { sysConfigProp.load(SystemConfig.class.getClassLoader().getResourceAsStream(sysConfigPath));
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getinterface() {
return (String) getProperty("getinterface") ;
}
public static Object getProperty(String key) {
if (sysConfigProp != null && sysConfigProp.get(key) != null) {
return sysConfigProp.get(key);
}
return null;
}
下面是sysconfig.properties文件
getinterface=xxxxxxxxxx即远程接口的路径
远程接口调用的方法
private Result callPcUrl(String url, String inputParam) {
//Result是结果统一返回对象
String resultStr = "";
Result vo = new Result();
try {
vo.setRequestUrl(url);
vo.setRequestBody(inputParam);
;
JSONObject jsonResult = httpsRequestForBack(url, inputParam);
vo.setSuccess(jsonResult.getString("success"));
vo.setMessage(jsonResult.getString("message"));
vo.setData(jsonResult.getString("data"));
} catch (Exception e) {
logger.error("接口调用失败,参数:{}", inputParam, e);
vo.setNetStatus(false);
}
return vo;
}
httpsRequestForBack方法
/*
* @description 远程调用https请求并返回结果
* @author cjh
* @date 2022/3/1
* @param
* @return JSONObject
*/
public static JSONObject httpsRequestForBack(String url,String outputStr) {
JSONObject jsonObject=new JSONObject();
try {
SSLContext sslContext = SSLContextBuilder.create().useProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y) -> true).build();
CloseableHttpClient httpClient = HttpClientBuilder.create().setSSLContext(sslContext).setSSLHostnameVerifier((x, y) -> true).build();
HttpPost httpPost = new HttpPost(url);
// 设置请求的header,数据传输的格式
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
// 设置请求的参数
StringEntity entity = new StringEntity(outputStr, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
// 执行请求
HttpResponse response = httpClient.execute(httpPost);
String json2 = EntityUtils.toString(response.getEntity(), "utf-8");
jsonObject = JSONObject.parseObject(json2);
}catch (Exception e){
logger.error("发送HTTP请求失败:requestUrl:{},outputStr:{}",url,outputStr,e);
}
// 打印执行结果
System.out.println(jsonObject);
return jsonObject;
}
OK!