1、gradle添加包
implementation 'org.apache.httpcomponents:httpclient:4.5.1'
implementation 'commons-collections:commons-collections:3.2.2'
2、调用
import org.apache.commons.collections.MapUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Map;
import static org.jboss.logging.MDC.getMap;
/**
* Created with IDEA2018.3.2
* @ClassName: SchedulerTask
* @author:zhangzhao
* @Date:2019/3/18 9:54
* @Version 1.0
*/
@Component
public class SchedulerTask {
@Scheduled(cron="*/9 * * * * ?")
private void testing(){
try {
String url = "http://www.baidu.com/";
URIBuilder builder = null;
builder = new URIBuilder(url);
CloseableHttpClient httpClient = HttpClients.createDefault();
Map<String,Object> map=getMap();
if(MapUtils.isNotEmpty(map)){
for(Map.Entry<String,Object> entry:map.entrySet()){
builder.addParameter(entry.getKey(), String.valueOf(entry.getValue()));
}
url=builder.build().toString();
}
HttpGet get = new HttpGet(url);
// 增加超时设置
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000).build();
get.setConfig(requestConfig);
//发送GET请求
CloseableHttpResponse response = httpClient.execute(get);
//获取状态码
Integer responseStatus = response.getStatusLine().getStatusCode();
System.out.println("whhlyt" + response.getStatusLine().getStatusCode());
if (responseStatus == 200) {
// 不执行
} else {
// 发送短信,网站异常,发送短信通知
}
} catch (Exception e) {
e.printStackTrace();
}
}
}