一、初始方法
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<NameValuePair> paramList = new ArrayList<NameValuePair>();
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();
}
二、第一輪重構:參數(shù)化
字符串參數(shù)化
鍵值對參數(shù)化
斷言功能分離,該方法只負責http請求
public static String httpPost2(int timeout,String url,HashMap<String,String> headers,HashMap<String,String> 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<NameValuePair> paramList = new ArrayList<NameValuePair>();
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();
}
三、第二輪重構:參數(shù)封裝成bean
- 默認值:超時時間、編碼想取默認值,給不給都不會報錯
- 參數(shù)化后變量個數(shù)太多,不利于閱讀和維護
什么時候用入?yún)?,什么時候用bean封裝入?yún)ⅲ?br> 個數(shù)少的時候(4個以內(nèi)),直接參數(shù)化,個數(shù)多的時候,將參數(shù)封裝成javabean
package com.guoyasoft.tools.http;
import java.util.HashMap;
public class ApacheHttpBean {
private int timeout=6000;
private String url;
private HashMap<String,String> headers=new HashMap<String,String>();
private HashMap<String,String> params=new HashMap<String,String>();
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<String, String> getHeaders() {
return headers;
}
public void setHeaders(HashMap<String, String> headers) {
this.headers = headers;
}
public HashMap<String, String> getParams() {
return params;
}
public void setParams(HashMap<String, String> 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<NameValuePair> paramList = new ArrayList<NameValuePair>();
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作為數(shù)據(jù)源

image.png

image.png
<!-- 讀取csv文件 -->
<dependency>
<groupId>net.sourceforge.javacsv</groupId>
<artifactId>javacsv</artifactId>
<version>2.0</version>
</dependency>
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 固定大?。簲?shù)組,先確定大小,再以下標存放數(shù)據(jù),最后以下標取數(shù)據(jù)
* 1.2 不固定大?。篈rrayList,先add(數(shù)據(jù))往里面添加數(shù)據(jù)(不能指定位置,因為是邊加邊擴,只能加到最后一個),get()以下標取數(shù)據(jù)
* 1.3 不固定大小,且要按照標簽存放,按照標簽取數(shù)據(jù):HashMap,先以put(“變量名”,數(shù)據(jù))存數(shù)據(jù),再以get("變量名")取數(shù)據(jù)
*
* 2. 循環(huán)
* 2.1 for循環(huán):for(變量類型 定義一個變量=初始值;最大值;增量),知道最大循環(huán)次數(shù)的情況
* 2.2 while循環(huán):不知道要多少次,只知道一個結束的標識,循環(huán)到false為止
*
* 3. if(帥嗎?){ok}else if(高嗎){ok}else if(有錢嗎?){ok}else{滾犢子!}
*
* 4. try{業(yè)務邏輯}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 倒數(shù)第一個:方法名
* 4.2.6 倒數(shù)第二個:類名
* 4.2.7 倒數(shù)第三個:包名
*/
public static Object[][] readCSV(String csvFilePath) {
//try{業(yè)務代碼}catch(Exception e){如果做業(yè)務的過程中出了錯,的異常處理邏輯}
try {
//容器:對象少的時候,直接把對象列出來;當對象很多的時候,要用一個容器裝起來打包
ArrayList<String[]> csvFileList = new ArrayList<String[]>();
// 這個不用背,只要看得懂會用就行。創(chuàng)建CSV讀對象 例如:CsvReader(文件路徑,分隔符,編碼格式);
CsvReader reader = new CsvReader(csvFilePath, ',', Charset.forName("GBK"));
// 跳過表頭 如果需要表頭的話,這句可以忽略
reader.readHeaders();
// 逐行讀入除表頭的數(shù)據(jù)
//boolean變量:真假true或者false
while (reader.readRecord()) {
System.out.println(reader.getRawRecord());
//將一行的字符串按照“,”逗號分成多列,存放到String[]數(shù)組中
//再將這個string[]放到list容器中存起來
csvFileList.add(reader.getValues());
}
//數(shù)據(jù)取完了,關閉文件
reader.close();
// 遍歷讀取的CSV文件
//for是一個整數(shù)次的循環(huán),三個參數(shù):最小值,最大值,增量,取個變量名存放每次循環(huán)的序列值
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 {
// 創(chuàng)建CSV寫對象 例如:CsvWriter(文件路徑,分隔符,編碼格式);
CsvWriter csvWriter = new CsvWriter(csvFilePath, ',', Charset.forName("UTF-8"));
// 寫表頭
String[] csvHeaders = { "編號", "姓名", "年齡" };
csvWriter.writeRecord(csvHeaders);
// 寫內(nèi)容
for (int i = 0; i < 20; i++) {
String[] csvContent = { i + "000000", "StemQ", "1" + i };
csvWriter.writeRecord(csvContent);
}
csvWriter.close();
System.out.println("--------CSV文件已經(jīng)寫入--------");
} 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);
}
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="suit1">
<test name="test0" preserve-order="true" enabled="true">
<parameter name="url" value="http://47.98.226.232:8080/guoya-medium/user/login.action"></parameter>
<classes>
<class name="com.guoyasoft.tools.http.TestHttp">
<methods>
<include name="testHttpCsv" />
</methods>
</class>
</classes>
</test>
</suite>