本人在做接口自动化时候,因为服务器不稳定造成可能的用例失败,但这个失败表象只是在获取响应实体的json对象时为空,在后期排查问题时可能造成困扰,所以特意加了一个获取响应失败的通知,目的就是即使了解到服务器异常。暂时用的是免费的alertover,用了很久,简单可靠是它的优点,后续会加入微信提醒。分享代码,供大家参考。
下面是获取响应实体的json对象的方法(可忽略某一些封装方法):
/** * 获取响应实体 * * @param request 请求对象 * @return 返回json类型的对象 */ public static JSONObject getHttpResponseEntityByJson(HttpRequestBase request) { RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeOut).setConnectTimeout(timeOut).setSocketTimeout(timeOut).build(); request.setConfig(requestConfig); String url = request.getURI().toString(); output(TAB + TAB + "请求地址:" + url); JSONObject jsonObject = null; CloseableHttpResponse response = null;// 创建响应对象 long data_size = 0;// 用于存放数据大小 Map<String, String> info = getRequestInfo(request); String api_name = info.get("api_name"); String type = info.get("type"); String host_name = info.get("host_name"); String method = info.get("method"); String params = info.get("params"); output(TAB + TAB + "请求参数是:" + params); request.addHeader(HTTP.USER_AGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36");// 符合应用防火墙 // 如果已经设置过cookie的话,不设置默认cookie,这里之前设置过的header只有user_agent if (cookies != null && cookies.length() > 1 && request.getAllHeaders().length < 2) request.addHeader("Cookie", cookies);// 添加cookie if (mark == 0) mark = getMark() / 100; Date start = getDate();// 记录开始时间 try { response = httpsClient.execute(request); } catch (Exception e) { output("请求发生错误!", e); new AlertOver("接口请求失败", "参数:" + params + LINE + "错误:" + Arrays.toString(e.getStackTrace()), url).sendMessage(); } Date end = getDate();// 记录结束时间 double elapsed_time = getTimeDiffer(start, end);// 获取响应耗时 if (response == null) return null; Header[] header = response.getAllHeaders();// 获取响应header int headerSize = header.length; for (int i = 0; i < headerSize; i++) {// 遍历header String name = header[i].getName(); if (name.equals("Set-Cookie")) {// 处理cookies if (cookieKey) { cookies = null; cookieKey = false; } String value = header[i].getValue().split(";")[0]; if (cookies == null)// 拼接cookie cookies = value; cookies = cookies + ";" + value; } } // 更新cookieKey if (cookieKey == false && cookies != null) cookieKey = true; int status = response.getStatusLine().getStatusCode();// 获取响应状态 HttpEntity entity = response.getEntity();// 获取响应实体 data_size = entity.getContentLength();// 获取相应数据大小 if (data_size == -1) // 如果为-1,则重置data_size data_size = 0; String content = null; try { content = EntityUtils.toString(entity, "utf-8");// 用string接收响应实体 EntityUtils.consume(entity);// 消耗响应实体 } catch (ParseException e1) { output("解析响应实体异常!", e1); } catch (IOException e1) { output("解析响应实体时java IO 异常!", e1); } // 解析响应 try { response.close(); } catch (IOException e2) { output("响应关闭失败!", e2); } if (data_size == 0) {// 如果被重置或者没有获取到,则data_size等于解析string大小 try { data_size = content.length(); } catch (Exception e) { data_size = 1; output("获取响应长度异常!", e); } } if (status == 200) { try { jsonObject = JSONObject.fromObject(content); } catch (Exception e) { jsonObject.put("content", content); // output("响应内容:" + content, e); output("响应内容不是 json 格式的!,默认转换为 json 格式!"); } } else { output("状态码错误,相应内容:" + content); } MySqlTest.getInstance().saveApiTestDate(host_name, api_name, data_size, elapsed_time, status, type, mark, method); return jsonObject; }
下面是alertover类的代码,比较简单:
package source; import org.apache.http.client.methods.HttpPost; import net.sf.json.JSONObject; public class AlertOver extends ApiLibrary { public String title; public String content; public String murl; public AlertOver() { this("test title", "test content!"); } public AlertOver(String title, String content) { this.title = title; this.content = content; } public AlertOver(String title, String content,String url) { this(title,content); this.murl = url; } public static void main(String[] args) { AlertOver alertOver = new AlertOver("我是测试!", "我是内容!" + getNow(),"https://www.baidu.com"); alertOver.sendMessage(); testOver(); } /** * 发送消息 * * @return */ public JSONObject sendMessage() { String url = "https://api.alertover.com/v1/alert"; String source = "**********";// mi5s发送源id String receiver = "********************"; JSONObject jsonObject = new JSONObject();// 新建json对象 jsonObject.put("source", source);// 添加发送源id jsonObject.put("receiver", receiver);// 添加接收组id jsonObject.put("content", content);// 发送内容 jsonObject.put("title", title);// 发送标题 jsonObject.put("url", murl);// 发送url jsonObject.put("sound", "pianobar");// 提示音 HttpPost httpPost = getHttpPost(url, jsonObject); JSONObject response = getHttpResponseEntityByJson(httpPost); // output(response); return response; } }
末了宣传一下QQ群:群号:340964272