一、初始方法
public static void httpPost() throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
String url = "http://47.98.226.232:8080/guoya-medium/user/login.action";
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(6000).setConnectTimeout(6000).build();// 设置请求和传输超时时间
httpPost.setConfig(requestConfig);
httpPost.addHeader("Host", "47.98.226.232:8080");
httpPost.addHeader("Connection", "keep-alive");
List paramList = new ArrayList();
paramList.add(new BasicNameValuePair("userName", "guoya"));
paramList.add(new BasicNameValuePair("password",
"46da9da65fae31c690e7c391f37b085a"));
paramList.add(new BasicNameValuePair("checkCode", "12345"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
httpResponse = httpClient.execute(httpPost);
reader = new BufferedReader(new InputStreamReader(httpResponse
.getEntity().getContent(), "UTF-8"));
String inputLine;
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
} catch (Exception var) {
var.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
if (httpResponse != null) {
httpResponse.close();
}
httpClient.close();
}
System.out.println(response.toString());
boolean isSuccess = response.toString().contains("班级类型");
Assert.assertEquals(true, isSuccess);
// return response.toString();
}
二、第一轮重构:参数化
字符串参数化
键值对参数化
断言功能分离,该方法只负责http请求
public static String httpPost2(int timeout,String url,HashMap headers,HashMap params,String encode) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
//String url = "http://47.98.226.232:8080/guoya-medium/user/login.action";
HttpPost httpPost = new HttpPost(url);
// RequestConfig requestConfig = RequestConfig.custom()
// .setSocketTimeout(6000).setConnectTimeout(6000).build();// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(timeout).setConnectTimeout(timeout).build();// 设置请求和传输超时时间
httpPost.setConfig(requestConfig);
Iterator iterator=headers.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry entry = (Map.Entry) iterator.next();
httpPost.addHeader(entry.getKey().toString(), entry.getValue().toString());
}
List paramList = new ArrayList();
iterator=params.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry entry = (Map.Entry) iterator.next();
paramList.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString()));
}
// paramList.add(new BasicNameValuePair("userName", "guoya"));
// paramList.add(new BasicNameValuePair("password",
// "46da9da65fae31c690e7c391f37b085a"));
// paramList.add(new BasicNameValuePair("checkCode", "12345"));
try {
//httpPost.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
httpPost.setEntity(new UrlEncodedFormEntity(paramList, encode));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
httpResponse = httpClient.execute(httpPost);
// reader = new BufferedReader(new InputStreamReader(httpResponse
// .getEntity().getContent(), "UTF-8"));
reader = new BufferedReader(new InputStreamReader(httpResponse
.getEntity().getContent(), encode));
String inputLine;
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
} catch (Exception var) {
var.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
if (httpResponse != null) {
httpResponse.close();
}
httpClient.close();
}
System.out.println(response.toString());
// boolean isSuccess = response.toString().contains("班级类型");
// Assert.assertEquals(true, isSuccess);
return response.toString();
}
三、第二轮重构:参数封装成bean
- 默认值:超时时间、编码想取默认值,给不给都不会报错
- 参数化后变量个数太多,不利于阅读和维护
什么时候用入参,什么时候用bean封装入参?
个数少的时候(4个以内),直接参数化,个数多的时候,将参数封装成javabean
package com.guoyasoft.tools.http;
import java.util.HashMap;
public class ApacheHttpBean {
private int timeout=6000;
private String url;
private HashMap headers=new HashMap();
private HashMap params=new HashMap();
private String encode="UTF-8";
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public HashMap getHeaders() {
return headers;
}
public void setHeaders(HashMap headers) {
this.headers = headers;
}
public HashMap getParams() {
return params;
}
public void setParams(HashMap params) {
this.params = params;
}
public String getEncode() {
return encode;
}
public void setEncode(String encode) {
this.encode = encode;
}
}
public static String httpPost2(ApacheHttpBean params) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
//String url = "http://47.98.226.232:8080/guoya-medium/user/login.action";
HttpPost httpPost = new HttpPost(params.getUrl());
// RequestConfig requestConfig = RequestConfig.custom()
// .setSocketTimeout(6000).setConnectTimeout(6000).build();// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(params.getTimeout()).setConnectTimeout(params.getTimeout()).build();// 设置请求和传输超时时间
httpPost.setConfig(requestConfig);
Iterator iterator=params.getHeaders().entrySet().iterator();
while(iterator.hasNext()){
Map.Entry entry = (Map.Entry) iterator.next();
httpPost.addHeader(entry.getKey().toString(), entry.getValue().toString());
}
List paramList = new ArrayList();
iterator=params.getParams().entrySet().iterator();
while(iterator.hasNext()){
Map.Entry entry = (Map.Entry) iterator.next();
paramList.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString()));
}
// paramList.add(new BasicNameValuePair("userName", "guoya"));
// paramList.add(new BasicNameValuePair("password",
// "46da9da65fae31c690e7c391f37b085a"));
// paramList.add(new BasicNameValuePair("checkCode", "12345"));
try {
//httpPost.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
httpPost.setEntity(new UrlEncodedFormEntity(paramList, params.getEncode()));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
httpResponse = httpClient.execute(httpPost);
// reader = new BufferedReader(new InputStreamReader(httpResponse
// .getEntity().getContent(), "UTF-8"));
reader = new BufferedReader(new InputStreamReader(httpResponse
.getEntity().getContent(), params.getEncode()));
String inputLine;
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
} catch (Exception var) {
var.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
if (httpResponse != null) {
httpResponse.close();
}
httpClient.close();
}
System.out.println(response.toString());
// boolean isSuccess = response.toString().contains("班级类型");
// Assert.assertEquals(true, isSuccess);
return response.toString();
}
package com.guoyasoft.tools.http;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestHttp {
@Test
public void testHttp() throws Exception{
ApacheHttpBean bean=new ApacheHttpBean();
bean.setUrl("http://47.98.226.232:8080/guoya-medium/user/login.action");
bean.getHeaders().put("Host", "47.98.226.232:8080");
bean.getHeaders().put("Connection", "keep-alive");
bean.getParams().put("userName", "guoya");
bean.getParams().put("password", "46da9da65fae31c690e7c391f37b085a");
bean.getParams().put("checkCode", "12345");
String response=ApacheHttp.httpPost2(bean);
System.out.println(response);
boolean isSuccess=response.contains("真实姓名");
Assert.assertEquals(true, isSuccess);
}
}
第四轮重构:使用csv作为数据源
net.sourceforge.javacsv
javacsv
2.0
package com.guoyasoft.tools.csv;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
public class CSVReader {
/**
* 1. 容器:
* 1.1 固定大小:数组,先确定大小,再以下标存放数据,最后以下标取数据
* 1.2 不固定大小:ArrayList,先add(数据)往里面添加数据(不能指定位置,因为是边加边扩,只能加到最后一个),get()以下标取数据
* 1.3 不固定大小,且要按照标签存放,按照标签取数据:HashMap,先以put(“变量名”,数据)存数据,再以get("变量名")取数据
*
* 2. 循环
* 2.1 for循环:for(变量类型 定义一个变量=初始值;最大值;增量),知道最大循环次数的情况
* 2.2 while循环:不知道要多少次,只知道一个结束的标识,循环到false为止
*
* 3. if(帅吗?){ok}else if(高吗){ok}else if(有钱吗?){ok}else{滚犊子!}
*
* 4. try{业务逻辑}catch(Exception e){异常处理逻辑}
* 4.1 e.printStackTrace():打印报错日志信息
* 4.2 错误日志阅读方式:
* 4.2.1 从上往下读,也就是找到日志报错开始的地方
* 4.2.2 第一行是报错类型
* 4.2.3 后面是具体位置,at在哪儿,然后从后往前读
* 4.2.4 ()括号里面是哪个java文件的哪一行报错
* 4.2.5 倒数第一个:方法名
* 4.2.6 倒数第二个:类名
* 4.2.7 倒数第三个:包名
*/
public static Object[][] readCSV(String csvFilePath) {
//try{业务代码}catch(Exception e){如果做业务的过程中出了错,的异常处理逻辑}
try {
//容器:对象少的时候,直接把对象列出来;当对象很多的时候,要用一个容器装起来打包
ArrayList csvFileList = new ArrayList();
// 这个不用背,只要看得懂会用就行。创建CSV读对象 例如:CsvReader(文件路径,分隔符,编码格式);
CsvReader reader = new CsvReader(csvFilePath, ',', Charset.forName("GBK"));
// 跳过表头 如果需要表头的话,这句可以忽略
reader.readHeaders();
// 逐行读入除表头的数据
//boolean变量:真假true或者false
while (reader.readRecord()) {
System.out.println(reader.getRawRecord());
//将一行的字符串按照“,”逗号分成多列,存放到String[]数组中
//再将这个string[]放到list容器中存起来
csvFileList.add(reader.getValues());
}
//数据取完了,关闭文件
reader.close();
// 遍历读取的CSV文件
//for是一个整数次的循环,三个参数:最小值,最大值,增量,取个变量名存放每次循环的序列值
Object[][] result=new Object[csvFileList.size()][5];
for (int row = 0; row < csvFileList.size(); row++) {
result[row]=csvFileList.get(row);
}
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void writeCSV(String csvFilePath) {
try {
// 创建CSV写对象 例如:CsvWriter(文件路径,分隔符,编码格式);
CsvWriter csvWriter = new CsvWriter(csvFilePath, ',', Charset.forName("UTF-8"));
// 写表头
String[] csvHeaders = { "编号", "姓名", "年龄" };
csvWriter.writeRecord(csvHeaders);
// 写内容
for (int i = 0; i < 20; i++) {
String[] csvContent = { i + "000000", "StemQ", "1" + i };
csvWriter.writeRecord(csvContent);
}
csvWriter.close();
System.out.println("--------CSV文件已经写入--------");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//JavaCSV.writeCSV(csvFilePath);
CSVReader.readCSV("C:\\softwareData\\workspace\\guoya-test\\src\\main\\resources\\testNG\\searchData.csv");
}
}
package com.guoyasoft.tools.http;
import org.testng.annotations.DataProvider;
import com.guoyasoft.tools.csv.CSVReader;
public class ApacheHttpDataProvider {
@DataProvider(name="loginUser")
public static Object[][] getLoginUser(){
Object[][] objs=CSVReader.readCSV("src/main/java/com/guoyasoft/tools/http/loginUsers.csv");
return objs;
}
}
@Test(dataProvider="loginUser",dataProviderClass=com.guoyasoft.tools.http.ApacheHttpDataProvider.class)
public void testHttpCsv(ITestContext context, String userName,String password,String checkCode,String exception) throws Exception{
ApacheHttpBean bean=new ApacheHttpBean();
String url=context.getCurrentXmlTest().getParameter("url");
bean.setUrl(url);
// bean.setUrl("http://47.98.226.232:8080/guoya-medium/user/login.action");
// bean.getHeaders().put("Host", "47.98.226.232:8080");
// bean.getHeaders().put("Connection", "keep-alive");
bean.getParams().put("userName", userName);
bean.getParams().put("password", password);
bean.getParams().put("checkCode", checkCode);
String response=ApacheHttp.httpPost2(bean);
System.out.println(response);
boolean isSuccess=response.contains(exception);
Assert.assertEquals(true, isSuccess);
}