httpclient封装获取响应实体和接口信息的方法

  1. //获取post响应,暂无header设置  
  2.     public JSONObject getHttpResponseEntityByJson(CloseableHttpClient httpClient, HttpPost httpPost) throws ClientProtocolException, IOException, SQLException, JSONException {  
  3.         //在请求中明确定义不要进行压缩    
  4. //      httpPost.setHeader("Accept-Encoding", "identity");   
  5.         HttpResponse response = null;//创建响应对象  
  6.         long date_size = 0;//用于存放数据大小  
  7.         String api_name = getApiName(httpPost);//获取接口名称  
  8.         String type = getProtocolType(httpPost);//获取协议类型  
  9.         String host_name = getHostName(httpPost);//获取hsot主机名称  
  10.         Date start = getDate();//记录开始时间  
  11.         response = httpClient.execute(httpPost);//获取响应  
  12.         Date end = getDate();//记录结束时间  
  13.         double elapsed_time= outputTimeDiffer(start, end, "接口:" + api_name);//获取响应耗时  
  14.         int status = response.getStatusLine().getStatusCode();//获取响应状态  
  15.         if (status == HttpStatus.SC_OK) {//判断一下返回状态  
  16.             output("host:" + host_name, "接口:"+ api_name + "请求成功!");  
  17.             } else {  
  18.                 output(response.getStatusLine().getStatusCode() + LINE + "请求失败!");  
  19.             }  
  20.         HttpEntity entity = response.getEntity();//获取响应实体  
  21.         data_size = entity.getContentLength();//获取相应数据大小  
  22.         if (data_size == -1) {//如果为-1,则重置date_size  
  23.             date_size = 0;  
  24.         }  
  25.         String content = EntityUtils.toString(entity);//解析响应  
  26.         if (date_size == 0) {//如果被重置或者没有获取到,则date_size等于解析string大小  
  27.             date_size = content.length();  
  28.         }  
  29.         JSONObject jsonObject = new JSONObject(content);//转换json  
  30.         LocalMySql.getInstance().saveApiTestDate(host_name, api_name, date_size, elapsed_time, status, type);  
  31. //      httpClient.close();//关闭客户端  
  32.         return jsonObject;  
  33.     }  
  34.     //获取get接口响应,暂无header设置  
  35.     public JSONObject getHttpResponseEntityByJson(CloseableHttpClient httpClient, HttpGet httpGet) throws ClientProtocolException, IOException, JSONException, SQLException {  
  36.         //在请求中明确定义不要进行压缩  
  37. //      httpGet.setHeader("Accept-Encoding", "identity");   
  38.         HttpResponse response = null;  
  39.         long date_size = 0;  
  40.         String api_name = getApiName(httpGet);  
  41.         String type = getProtocolType(httpGet);  
  42.         Date start = getDate();  
  43.         response = httpClient.execute(httpGet);  
  44.         Date end = getDate();  
  45.         double elapsed_time= outputTimeDiffer(start, end, "接口:" + api_name);  
  46.         String host_name = getHostName(httpGet);  
  47.         int status = response.getStatusLine().getStatusCode();  
  48.         if (status == HttpStatus.SC_OK) {//判断一下返回状态  
  49.             output("host:" + host_name, "接口:"+ api_name + "请求成功!");  
  50.             } else {  
  51.                 output(response.getStatusLine().getStatusCode() + LINE + "请求失败!");  
  52.             }  
  53.         HttpEntity entity = response.getEntity();  
  54.         data_size = entity.getContentLength();  
  55.         if (data_size == -1) {  
  56.             date_size = 0;  
  57.         }  
  58.         String content = EntityUtils.toString(entity);  
  59.         if (date_size == 0) {  
  60.             date_size = content.length();  
  61.         }  
  62.         JSONObject jsonObject = new JSONObject(content);  
  63.         LocalMySql.getInstance().saveApiTestDate(host_name, api_name, date_size, elapsed_time, status, type);  
  64. //      httpClient.close();  
  65.         return jsonObject;  
  66.     }  
 
  1. //获取post响应,暂无header设置 public JSONObject getHttpResponseEntityByJson(CloseableHttpClient httpClient, HttpPost httpPost) throws ClientProtocolException, IOException, SQLException, JSONException { //在请求中明确定义不要进行压缩 // httpPost.setHeader("Accept-Encoding", "identity"); HttpResponse response = null;//创建响应对象 long date_size = 0;//用于存放数据大小 String api_name = getApiName(httpPost);//获取接口名称 String type = getProtocolType(httpPost);//获取协议类型 String host_name = getHostName(httpPost);//获取hsot主机名称 Date start = getDate();//记录开始时间 response = httpClient.execute(httpPost);//获取响应 Date end = getDate();//记录结束时间 double elapsed_time= outputTimeDiffer(start, end, "接口:" + api_name);//获取响应耗时 int status = response.getStatusLine().getStatusCode();//获取响应状态 if (status == HttpStatus.SC_OK) {//判断一下返回状态 output("host:" + host_name, "接口:"+ api_name + "请求成功!"); } else { output(response.getStatusLine().getStatusCode() + LINE + "请求失败!"); } HttpEntity entity = response.getEntity();//获取响应实体 data_size = entity.getContentLength();//获取相应数据大小 if (data_size == -1) {//如果为-1,则重置date_size date_size = 0; } String content = EntityUtils.toString(entity);//解析响应 if (date_size == 0) {//如果被重置或者没有获取到,则date_size等于解析string大小 date_size = content.length(); } JSONObject jsonObject = new JSONObject(content);//转换json LocalMySql.getInstance().saveApiTestDate(host_name, api_name, date_size, elapsed_time, status, type); // httpClient.close();//关闭客户端 return jsonObject; } //获取get接口响应,暂无header设置 public JSONObject getHttpResponseEntityByJson(CloseableHttpClient httpClient, HttpGet httpGet) throws ClientProtocolException, IOException, JSONException, SQLException { //在请求中明确定义不要进行压缩 // httpGet.setHeader("Accept-Encoding", "identity"); HttpResponse response = null; long date_size = 0; String api_name = getApiName(httpGet); String type = getProtocolType(httpGet); Date start = getDate(); response = httpClient.execute(httpGet); Date end = getDate(); double elapsed_time= outputTimeDiffer(start, end, "接口:" + api_name); String host_name = getHostName(httpGet); int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) {//判断一下返回状态 output("host:" + host_name, "接口:"+ api_name + "请求成功!"); } else { output(response.getStatusLine().getStatusCode() + LINE + "请求失败!"); } HttpEntity entity = response.getEntity(); data_size = entity.getContentLength(); if (data_size == -1) { date_size = 0; } String content = EntityUtils.toString(entity); if (date_size == 0) { date_size = content.length(); } JSONObject jsonObject = new JSONObject(content); LocalMySql.getInstance().saveApiTestDate(host_name, api_name, date_size, elapsed_time, status, type); // httpClient.close(); return jsonObject; }


中间使用了本地数据库,将收集的信息存入本地数据库里面,以便以后统计。代码如下:

 

 

[java] view plain copy print?

  1.     //保存接口测试数据的方法  
  2.     public void saveApiTestDate(String host_name, String api_name, long date_size, double elapsed_time, int status, String type) throws SQLException {  
  3.         getConnection();  
  4.         if (!connection.isClosed()) {  
  5.             outputSuccess();  
  6.             Statement statement = connection.createStatement();  
  7.             String sql = "INSERT INTO api_result (host_name,api_name,date_size,elapsed_time,status,type) VALUES ('"+host_name+"','"+api_name+"',"  
  8.             +date_size+","+ elapsed_time + "," + status + ",'" + type +"');";  
  9. //          output(sql);  
  10.             statement.executeUpdate(sql);  
  11.         }  
  12.     }  
//保存接口测试数据的方法
	public void saveApiTestDate(String host_name, String api_name, long date_size, double elapsed_time, int status, String type) throws SQLException {
		getConnection();
		if (!connection.isClosed()) {
			outputSuccess();
			Statement statement = connection.createStatement();
			String sql = "INSERT INTO api_result (host_name,api_name,date_size,elapsed_time,status,type) VALUES ('"+host_name+"','"+api_name+"',"
			+date_size+","+ elapsed_time + "," + status + ",'" + type +"');";
//			output(sql);
			statement.executeUpdate(sql);
		}
	}

中间用到了一些自己封装的方法:

 

 

[java] view plain copy print?

  1. //获取json数据中的相应值  
  2. public String getJsonValue(String jsonString, String key) throws JSONException {  
  3.        String JsonValue = null;  
  4.        if (jsonString == null || jsonString.trim().length() < 1) {//排除为空和空格  
  5.         return null;  
  6.         }  
  7.        JSONObject obj1 = new JSONObject(jsonString);  
  8.        JsonValue = (String) obj1.getString(key);  
  9.        return JsonValue;//返回对应值  
  10.    }  
  11. //获取json数据中的相应值  
  12. public String getJsonValue(JSONObject jsonObject, String key)    {  
  13.        String JsonValue = "··-·";  
  14.        try {  
  15.         JsonValue = (String) jsonObject.getString(key);  
  16.     } catch (JSONException e) {  
  17.         output("json数据错误!");  
  18.         output(e.toString());  
  19.     }  
  20.        return JsonValue;//返回对应值  
  21.    }  
  22. //把json数据转化为参数  
  23. public String changeJsonToArguments(JSONObject argument) {  
  24.     String one = argument.toString();  
  25.         String two ="?" + one.substring(1, one.length()-1).replace(",", "&").replace(":", "=").replace("\"", "");  
  26.         return two;  
  27.         }  
  28. //获取接口名称  
  29. public String getApiName(HttpGet httpGet) {  
  30.     String url = getUrl(httpGet);  
  31.     String apiName = url.substring(url.indexOf("m/") + 1);  
  32.     return apiName;  
  33. }  
  34. //获取接口名称  
  35. public String getApiName(HttpPost httpPost) {  
  36.     String url = getUrl(httpPost);  
  37.     String apiName = url.substring(url.indexOf("m/") + 1);  
  38.     return apiName;  
  39. }  
  40. //获取host名称  
  41. public String getHostName(HttpPost httpPost) {  
  42.     String url = getUrl(httpPost);  
  43.     String host = url.substring(url.indexOf("//") + 2, url.indexOf("m/") + 2);  
  44.     return host;  
  45. }  
  46. //获取host名称  
  47. public String getHostName(HttpGet httpGet) {  
  48.     String url = getUrl(httpGet);  
  49.     String host = url.substring(url.indexOf("//") + 2, url.indexOf("m/") + 2);  
  50.     return host;  
  51. }  
  52. //获取url  
  53. public String getUrl(HttpGet httpGet) {  
  54.     String uri = httpGet.getURI().toString();  
  55.     String url = uri.substring(0, uri.indexOf("?"));  
  56.     return url;  
  57. }  
  58. //获取url  
  59. public String getUrl(HttpPost httpPost) {  
  60.     String url = httpPost.getURI().toString();  
  61.     if (url.contains("?")) {  
  62.         url = url.substring(0, url.indexOf("?"));  
  63.     }  
  64.     return url;  
  65. }  
  66. //获取协议类型  
  67. public String getProtocolType(HttpGet httpGet) {  
  68.     String uri = httpGet.getURI().toString();  
  69.     String type = uri.substring(0, uri.indexOf("//") - 1);  
  70.     return type;  
  71. }  
  72. //获取协议类型  
  73. public String getProtocolType(HttpPost httpPost) {  
  74.     String uri = httpPost.getURI().toString();  
  75.     String type = uri.substring(0, uri.indexOf("//") - 1);  
  76.     return type;  
  77. }  
  78. //输出json  
  79. public void output(JSONObject jsonObject) {  
  80.     String info = jsonObject.toString().replaceAll(",", LINE);  
  81.     output(info);  
  82. }  

转载于:https://my.oschina.net/zhanggc/blog/1609692

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值