定时任务,LocalDateTime,在代码中调用其他项目的接口url

1.定时任务

1.在类上添加注解

@Component
@Configuration
@EnableScheduling

2.在类中方法上添加注解

@Scheduled(cron = "0 */2 * * * ?") //每两秒执行一次,通过cron表达式控制频率

2.LocalDateTime

LocalDateTime endTime = LocalDateTime.now();//获取当前时间   2022-11-28T10:42:48.538
LocalDateTime startTime = endTime.minusDays(3); //当前时间往前推3天
endTime.plusDays(1);//当前时间往后推一天

String end = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(endTime); //将日期格式化为指定格式

3.Http调用其他接口

1.导入相关依赖

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
</dependency>

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
</dependency>

2.工具类

点击查看代码
package com.hyl.utils;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import java.util.Map;

@Slf4j
public class HttpUtil {

	private static int HTTP_DEFAULT_TIMEOUT = 5000;

	public static final String SUCCESS = "success";

	private static URL url;
	private static HttpURLConnection con;

	/**
	 * post调用,传输map
	 *
	 * @param path
	 * @param params
	 * @return
	 * @throws IOException
	 */
	public static String send_post_request(String path, Map<String, String> params) throws IOException {
		return send_post_request(path, params, "UTF-8", HTTP_DEFAULT_TIMEOUT);
	}


	/**
	 * post调用
	 *
	 * @param path
	 * @param params
	 * @param encoding
	 * @return
	 * @throws IOException
	 */
	public static String send_post_request(String path, Map<String, String> params, String encoding, int timeout)
			throws IOException {
		if (StringUtils.isAnyBlank(path, encoding)) {
			log.info("path或encoding为空,path:{}, encoding: {}", path, encoding);
			return null;
		}
		InputStream inputStream = null;
		OutputStream outStream = null;
		HttpURLConnection conn = null;
		try {
			StringBuilder data = new StringBuilder();
			if (params != null) {
				for (Map.Entry<String, String> entry : params.entrySet()) {
					if(StringUtils.isBlank(entry.getKey()) || null == entry.getValue()) {
						continue;
					}
					data.append(entry.getKey()).append("=");
					data.append(URLEncoder.encode(entry.getValue(), encoding));
					data.append("&");
				}
			}
			if (data.length() > 0) {
				data.deleteCharAt(data.length() - 1);
			}
			log.info("====data:{}====", data.toString());
			byte[] entity = data.toString().getBytes();// 生成实体数据
			conn = (HttpURLConnection) new URL(path).openConnection();
			conn.setConnectTimeout(timeout);// 设置超时
			conn.setRequestMethod("POST");
			// 允许对外输出数据
			conn.setDoOutput(true);
			// 设定传送的内容类型是可序列化的java对象
			// (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
			conn.setRequestProperty("AppKey", "3");
			conn.setRequestProperty("Connection", "Keep-Alive");
			outStream = conn.getOutputStream();
			outStream.write(entity);
			log.info("responseCode: {}", conn.getResponseCode());
			if (conn.getResponseCode() == 200) {
				inputStream = conn.getInputStream();
				byte[] dateStream = readStream(inputStream);
				return new String(dateStream);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("http调用发生异常,错误信息:{}", e.getMessage());
		} finally {
			if (outStream != null) {
				outStream.close();
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
		return null;
	}
	/**
	 * 读取流
	 *
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	public static byte[] readStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[2048];
		int len = -1;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		outSteam.close();
		inStream.close();
		return outSteam.toByteArray();
	}

}

3.调用方法 发送请求

String url = "http://localhost:8088/emp-admin";
HashMap<Stirng,Stirng) map = new HashMap<>(){{
  put("id",1);
  put("name","张三")
}};
String result = HttpUtil.send_post_request(url, map);//若那边接口是Json格式,调用另一个方法,传入JsonObject()类型的参数即可
posted @   h*z  阅读(100)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示