俩个项目之间接口的调用,可以使用http请求
@SpringBootTest
@MapperScan("com.dao")
class SpringDaohangApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
}
@Test
public void httpTest(){
String loginurl = "http://192.168.0.214:8082/canteen/login";
JSONObject jsonObject = new JSONObject();
jsonObject.put("username","admin");
jsonObject.put("password","admin123");
String result = doPost(loginurl,jsonObject.toString());
JSONObject object = JSON.parseObject(result);
String token = (String) object.get("token");
String orderlist = "http://192.168.0.214:8082/canteen/order/list";
String orderlistresult = doGet(orderlist,token);
System.out.println(orderlistresult);
// System.out.println(object.get("token"));
// doPost(loginurl,null,)
}
@Test
public void test(){
System.out.println(userMapper.selectList(null).toString());
}
@Test
public Map<String,Object> upload_piture(HttpServletRequest request){
//将HttpServletRequest参数转成StandardMultipartHttpServletRequest 类型
StandardMultipartHttpServletRequest stRequest = (StandardMultipartHttpServletRequest)request;
//获取multipartFiles 对象组
MultiValueMap<String, MultipartFile> multipartFiles = stRequest.getMultiFileMap();
//获取MultipartFile 文件对象
MultipartFile multipartFile=multipartFiles.getFirst("file");
if (null == multipartFile || multipartFile.getSize() <= 0) {
return new HashMap<String,Object>(){{put("code",400);put("msg","请选择上传文件。");}};
}
String fileSavePath="C:\\Users\\11159\\Desktop\\图片\\1.jpg";
String originalName = multipartFile.getOriginalFilename();
String fileName= UUID.randomUUID().toString().replace("-", "");
String picNewName = fileName + originalName.substring(originalName.lastIndexOf("."));
String imgRealPath = fileSavePath + picNewName;
return new HashMap<String,Object>(){{put("code",200);put("msg",picNewName);}};
}
public static String doGet(String url,String token) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try {
// 通过址默认配置创建一个httpClient实例
httpClient = HttpClients.createDefault();
// 创建httpGet远程连接实例
HttpGet httpGet = new HttpGet(url);
// 设置请求头信息,鉴权
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Authorization", token);
// 设置配置请求参数
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
.setConnectionRequestTimeout(35000)// 请求超时时间
.setSocketTimeout(60000)// 数据读取超时时间
.build();
// 为httpGet实例设置配置
httpGet.setConfig(requestConfig);
// 执行get请求得到返回对象
response = httpClient.execute(httpGet);
// 通过返回对象获取返回数据
HttpEntity entity = response.getEntity();
// 通过EntityUtils中的toString方法将结果转换为字符串
result = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
throw new RuntimeException(e);
} finally {
// 关闭资源
if (null != response) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
public static String doPost(String httpUrl, String param) {
HttpURLConnection connection = null;
InputStream is = null;
OutputStream os = null;
BufferedReader br = null;
String result = null;
try {
URL url = new URL(httpUrl);
// 通过远程url连接对象打开连接
connection = (HttpURLConnection) url.openConnection();
// 设置连接请求方式
connection.setRequestMethod("POST");
// 设置连接主机服务器超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取主机服务器返回数据超时时间:60000毫秒
connection.setReadTimeout(60000);
// 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
connection.setDoOutput(true);
// 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
connection.setDoInput(true);
// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
connection.setRequestProperty("Content-Type", "application/json");
// 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
// connection.setRequestProperty("Authorization", token);
// 通过连接对象获取一个输出流
os = connection.getOutputStream();
// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
os.write(param.getBytes());
// 通过连接对象获取一个输入流,向远程读取
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 对输入流对象进行包装:charset根据工作项目组的要求来设置
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String temp = null;
// 循环遍历一行一行读取数据
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 断开与远程地址url的连接
connection.disconnect();
}
return result;
}
}
代码应用示例:
在食堂系统中调用电子卡系统中的扣费功能
/**
* 向电子卡管理系统发送请求
*/
public Boolean sendHttpRequest(PayDTO payDTO, String consumeNo) throws JsonProcessingException {
String loginurl = "http://localhost:9091/dev-api/card/login";
JSONObject jsonObject = new JSONObject();
jsonObject.put("username","root");
jsonObject.put("password","123456");
String result = doPost(loginurl,jsonObject.toString());
JSONObject object = JSON.parseObject(result);
String token = (String) object.get("token");
// 创建RestTemplate实例
RestTemplate restTemplate = new RestTemplate();
// 准备请求URL和请求参数
String targetUrl = "http://localhost:9091/dev-api/card/consume/pay";
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json"); // 根据接口要求设置合适的Content-Type
headers.set("Authorization", token); // 添加这行设置token
// 将payDTO转换为JSON格式
String payDtOJson = objectMapper.writeValueAsString(payDTO);
// 将consumeNo字符串转换为JSON格式
String consumeNoJson = "\"" + consumeNo + "\"";
// 创建请求体
HttpEntity<String> request = new HttpEntity<>(payDtOJson + "," + consumeNoJson, headers);
// 发送请求并获取响应
ResponseEntity<String> response = restTemplate.exchange(targetUrl, HttpMethod.POST, request, String.class);
// 处理响应数据
if (response.getStatusCode().is2xxSuccessful()) { // 如果响应状态码为2xx,表示请求成功
String responseBody = response.getBody();
//System.out.println("=============================>"+responseBody); // 处理响应数据,这里只是简单打印到控制台
return (responseBody.equals("true")? true:false);
} else {
//System.out.println("请求失败,响应状态码:" + response.getStatusCode());
return false;
}
}
电子卡中暴露的接口:
/**
* 扣卡支付消费记录
*/
@Log(title = "扣卡支付消费记录", businessType = BusinessType.INSERT)
@PostMapping("/pay")
public Boolean pay(@RequestBody PayDTO body,String consumeNo)
{
return payService.pay(body,consumeNo);
}