优雅的写init方法

怎么写出高质量的init方法,以下是demo可参考实现,代码实现。
在这里插入图片描述在这里插入图片描述

public class BaseTestController {
    private UnitTest unitTest;
    
    public void init(String url, String accessToken){
        unitTest = UnitTest.getNewInstance();
        unitTest.setHost(url);
        unitTest.setClientKey(accessToken);
    }
    
    public void init(String url,String archiveId,String userMobile){
        unitTest = UnitTest.getNewInstance();
        unitTest.setHost(url);
        unitTest.setArchiveId(archiveId);
        unitTest.setUserMobile(userMobile);
        setClientKey();
    }
    
    public void init(String url,String simulatedLandingUrl,String archiveId,String userMobile){
        unitTest = UnitTest.getNewInstance();
        unitTest.setHost(url);
        unitTest.setArchiveId(archiveId);
        unitTest.setUserMobile(userMobile);
        unitTest.setSimulatedLandingUrl(simulatedLandingUrl);
        setClientKey();
    }
    
    public void initNew(String url,String serverAddr,String userMobile, String password){
        unitTest = UnitTest.getNewInstance();
        unitTest.setHost(url);
        unitTest.setPassword(password);
        unitTest.setUserMobile(userMobile);
        unitTest.setSimulatedLandingUrl(serverAddr);
        unitTest.setClientKey(loginNew(unitTest.getUserMobile(), unitTest.getPassword()));
    }
    
    public void init(String url,String simulatedLandingUrl,String archiveId,String userMobile,String password){
        unitTest = UnitTest.getNewInstance();
        unitTest.setHost(url);
        unitTest.setArchiveId(archiveId);
        unitTest.setUserMobile(userMobile);
        unitTest.setPassword(password);
        unitTest.setSimulatedLandingUrl(simulatedLandingUrl);
        setClientKey();
    }
    public void initKdb(String url, String simulatedLandingUrl,String userMobile,String password){
        unitTest = UnitTest.getNewInstance();
        unitTest.setHost(url);
        unitTest.setSimulatedLandingUrl(simulatedLandingUrl);
        unitTest.setUserMobile(userMobile);
        unitTest.setPassword(password);
        setKdbClientKey();
    }
    private void setKdbClientKey() {
        unitTest.setClientKey(kdbLogin(unitTest.getUserMobile(), unitTest.getPassword()));
    }
    private String kdbLogin(String userMobile,String password){
        Map<String,String> paramMap = new HashMap<String,String>();
        paramMap.put("userMobile",userMobile);
        paramMap.put("loginPassword",password);
        String clientKey= null;
        try {
            JSONObject jsonObject = JSONObject.parseObject(HttpUtilNew.postJson(unitTest.getSimulatedLandingUrl(), paramMap));
            clientKey = jsonObject.getJSONObject("data").getString("clientKey");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return clientKey;
    }
    
    private String login(String userMobile, String archiveId, String password) throws Exception {
        Map<String,String> paramMap = new HashMap<String,String>();
        paramMap.put("USER_MOBILE",userMobile);
        paramMap.put("LOGIN_PASSWORD",password);
        paramMap.put("TOKEN", createToken());
        paramMap.put("action","simulatedLanding");
        String result = HttpUtil.post(unitTest.getSimulatedLandingUrl(), paramMap);
        try {
            unitTest.setClientKey(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    private String createToken(){
        String tokenCreate = EnCodeHelper.encode(unitTest.getUserMobile()+"HFT_OPEN_API_"+new Date().getDay());
        return tokenCreate;
    }
    
    public String getClientKey() {
        return unitTest.getClientKey();
    }
    
    private void setClientKey() {
        try {
            unitTest.setClientKey(login(unitTest.getUserMobile(), unitTest.getArchiveId(),unitTest.getPassword()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    public String getResult(){
        return unitTest.getResult();
    }
    
    public String postNewErp(Object param,String interfaceName) throws Exception {
        URL url = new URL(unitTest.getHost()+"/"+interfaceName);
        System.out.println(unitTest.getHost()+"/"+interfaceName);
        URLConnection urlConnection = url.openConnection();
        // 设置doOutput属性为true表示将使用此urlConnection写入数据
        urlConnection.setDoOutput(true);
        // 定义待写入数据的内容类型,我们设置为application/x-www-form-urlencoded类型
        urlConnection.setRequestProperty("content-type", "application/json");
      urlConnection.setRequestProperty("CLIENTKEY", "d48311413b02b444d5904d2690bb0eae");
        urlConnection.setRequestProperty("deviceType", "1");
        // 得到请求的输出流对象
        OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
        // 把数据写入请求的Body
        if(param instanceof BaseMapParam){
            BaseMapParam paramMap = (BaseMapParam)param;
            paramMap.setInteger("pageOffset", paramMap.getPageOffset());
            paramMap.setInteger("pageRows", paramMap.getPageRows());
            param = paramMap.getMap();
        }
        String jsonStr = JSON.toJSONString(param);
        out.write(jsonStr);
        out.flush();
        out.close();
        // 从服务器读取响应
        InputStream inputStream =  urlConnection.getInputStream();
        String encoding = urlConnection.getContentEncoding();
        String body = IOUtils.toString(inputStream, encoding);
        unitTest.setResult(body);
        return body;
    }
    
    public String postNewErp(Object param,String interfaceName,String clientKey) throws Exception {
        URL url = new URL(unitTest.getHost()+"/"+interfaceName);
        URLConnection urlConnection = url.openConnection();
        // 设置doOutput属性为true表示将使用此urlConnection写入数据
        urlConnection.setDoOutput(true);
        // 定义待写入数据的内容类型,我们设置为application/x-www-form-urlencoded类型
        urlConnection.setRequestProperty("content-type", "application/encrypt-json");
        urlConnection.setRequestProperty("CLIENTKEY", clientKey);
        urlConnection.setRequestProperty("deviceType", "1");
        // 得到请求的输出流对象
        OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
        // 把数据写入请求的Body
        if(param instanceof BaseMapParam){
            BaseMapParam paramMap = (BaseMapParam)param;
            paramMap.setInteger("pageOffset", paramMap.getPageOffset());
            paramMap.setInteger("pageRows", paramMap.getPageRows());
            param = paramMap.getMap();
        }
        String jsonStr = JSON.toJSONString(param);
        System.out.println("===========请求参数:" + jsonStr);
        out.write(AESHelper.encode(jsonStr));
        out.flush();
        out.close();
        // 从服务器读取响应
        InputStream inputStream =  urlConnection.getInputStream();
        String encoding = urlConnection.getContentEncoding();
        String body = IOUtils.toString(inputStream, encoding);
        unitTest.setResult(body);
        return body;
    }
    
    public String sendGet(String url, String param) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result.toString();
    }
    public String getNewErp(String interfaceName) throws Exception {
        URL url = new URL(unitTest.getHost()+"/"+interfaceName);
        URLConnection urlConnection = url.openConnection();
        // 定义待写入数据的内容类型,我们设置为application/x-www-form-urlencoded类型
        urlConnection.setRequestProperty("CLIENTKEY", unitTest.getClientKey());
        urlConnection.connect();
        // 从服务器读取响应
        BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        return in.lines().collect(Collectors.joining(""));
    }
    
    private String loginNew(String userMobile,String password){
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("passwordType",0);
        paramMap.put("userMobile",userMobile);
        paramMap.put("loginPassword",password);
        String loginResult = HttpUtil.postJson(unitTest.getSimulatedLandingUrl(), paramMap);
        JSONObject loginJosnObject = JSONObject.parseObject(loginResult);
        Integer errcode = loginJosnObject.getInteger("errCode");
        if (Const.ResponseCode.SUCCESS != errcode) {
            if (errcode.equals("1")) {
                throw new BusinessException("系统错误");
            } else {
                throw new BusinessException(loginJosnObject.getString("errMsg"));
            }
        }
        String dataStr = loginJosnObject.getString("data");
        JSONObject dataJsonObject = JSONObject.parseObject(dataStr);
        return dataJsonObject.getString("clientKey");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值