webservice连接是否可用

一、前言
在调用webservice服务前,验证webservice接口地址是否可用,是一项很有必要的工作,在参看了其他的博客后,记录下来
二、工具类代码

package com.sleb.springcloud.slebbatch.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 检验连接是否可用
 * @author : 追到乌云的尽头找太阳-(Jacob)
 * @date : 2019/12/11 9:49
 **/
@Component
public class ConnectionUtil {
    
    private static  final Logger log = LoggerFactory.getLogger(ConnectionUtil.class);

    private MailUtil mailUtil;
    public ConnectionUtil(MailUtil mailUtil) {
        this.mailUtil = mailUtil;
    }

    /**
     * 验证webservice是否可用
     *参数: webserviceUrl  webservice地址
     *返回值 : 可用返回true,不可用返回false   
     *@author :zlc(Jacob)
     *创建时间:2019/12/11
     */
    public boolean webServiceIsAvaiable(String webserviceUrl){
        boolean flag = false;
        int normalResponseCode = 200;
        try {
            URL  url = new URL(webserviceUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setUseCaches(false);
            urlConnection.setConnectTimeout(3000);
            if (normalResponseCode == urlConnection.getResponseCode()){
                flag = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("校验webservice服务不可用,异常信息为" + e.getMessage());
            try {
                mailUtil.sendMail("webservice服务不可用","webservice地址为"+webserviceUrl);
            }catch (Exception e1){
                e1.printStackTrace();
                log.error("发送邮件异常,异常信息为:"+ e1.getMessage());
            }
        }
        return flag;
    }
}

注释:,只需要一个url地址即可,不要传递webservice接口需要的参数。发送邮件的方法可以参看我的其他博客,
SpringBoot中发送邮件


版权声明:本文为chen15369337607原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。