接口自动化:淘宝的登录、搜索商品、确认订单、付款流程
1、http中有post、get、put、delet方法,需要一个独立的类来实现这些方法
package test;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.testng.Reporter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpMethod {
// get请求方法
public static CloseableHttpResponse get(String url) throws ClientProtocolException, IOException {
return get(url, null);
}
// Get 请求方法(带请求头信息)
public static CloseableHttpResponse get(String url, Map<String, String> headers)
throws ClientProtocolException, IOException {
// 创建一个可关闭的HttpClient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建一个HttpGet的请求对象
HttpGet httpget = new HttpGet(url);
// 加载请求头到httpget对象
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpget.addHeader(entry.getKey(), entry.getValue());
}
}
// 执行请求,相当于postman上点击发送按钮,然后赋值给HttpResponse对象接收
CloseableHttpResponse httpResponse = httpclient.execute(httpget);
return httpResponse;
}
//POST方法(如果不需要header可传入null),提交form表单(默认application/x-www-form-urlencoded)
public static CloseableHttpResponse postForm(String url, Map<String, String> params, Map<String, String> headers)
throws ClientProtocolException, IOException {
// 设置请求头数据传输格式,使用表单提交的方式,postman中有写
//headers.put("Content-Type","application/x-www-form-urlencoded");
return post(url, null, params, headers);
}
// POST方法,发送json格式(如果不需要header可传入null)
public static CloseableHttpResponse postJson(String url, String jsonString, Map<String, String> headers)
throws ClientProtocolException, IOException {
//准备请求头信息
headers.put("Content-Type", "application/json");//postman中有写
return post(url, jsonString, null, headers);
}
// POST方法
static CloseableHttpResponse post(String url, String jsonString, Map<String, String> params, Map<String, String> headers)
throws ClientProtocolException, IOException {
// 创建一个可关闭的HttpClient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建一个HttpPost的请求对象
HttpPost httppost = new HttpPost(url);
// 构造请求体,创建参数队列
if (jsonString != null && !"".equals(jsonString)) {
httppost.setEntity(new StringEntity(jsonString));
} else {
// 构造请求体,创建参数队列
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if (params != null && params.size() > 0) {
for (Map.Entry<String, String> entry : params.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
httppost.setEntity(new UrlEncodedFormEntity(nvps));
}
// 加载请求头到httppost对象
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httppost.addHeader(entry.getKey(), entry.getValue());
}
}
// 发送post请求
CloseableHttpResponse httpResponse = httpclient.execute(httppost);
return httpResponse;
}
public static int getStatusCode(CloseableHttpResponse response) {
int statusCode = response.getStatusLine().getStatusCode();
Reporter.log("响应码:" + statusCode);
return statusCode;
}
}
2、实现 登录 post请求 login.taobao.com、商品搜索 searchCommodity https://ai.taobao.com/search/index.htm get方法、提交订单 接口 https://buy.tmall.com/order/confirm_order.htm post方法、付款 https://kcart.alipay.com/web/bi.do
package test;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.testng.Reporter;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @ToDo 淘宝接口为https,本地调试需要在本地添加CA证书。http请求则不需要
* 接口自动化测试流程:buySomeThing()
* 淘宝网登录,商品搜索、下单、付款的购物流程
* 1、登录 post请求 login.taobao.com
* 2、商品搜索 searchCommodity https://ai.taobao.com/search/index.htm get方法
* 3、提交订单 接口 https://buy.tmall.com/order/confirm_order.htm post方法
* 4、付款 https://kcart.alipay.com/web/bi.do
*/
public class InterfaceTaobao {
public static void main(String[] args) throws Exception {
String url = "https://login.taobao.com/newlogin/login.do";
String payPassword = "11111";
String userCount = "1889299";//手机号
String goods = "水杯";
String loginpasswd = "11111";
buySomeThing(url,goods,userCount,loginpasswd,payPassword);
}
/**
* 淘宝购物的整个流程
*/
public static void buySomeThing(String baseURL, String goods,String userCount,String passWord,String payPassword) throws Exception {
CloseableHttpResponse closeableHttpResponse = null;
int resoponsCode = 0;//接口返回状态码
String responseString = null;//responseBody
//登录淘宝
closeableHttpResponse = loginTaobao(baseURL,userCount,passWord);
resoponsCode = HttpMethod.getStatusCode(closeableHttpResponse);
Reporter.log("接口返回状态码为:" + resoponsCode);
Assert.assertEquals(200, resoponsCode);
//得到登录信息,返回用户pid
responseString = EntityUtils.toString(closeableHttpResponse.getEntity());
List<Map<String, String>> restLogin = JSONObject.parseObject("[" + responseString + "]", List.class);
Map<String, String> mapLogin = restLogin.get(0);
String userID = mapLogin.get("pid");//用户id
//搜索
closeableHttpResponse = searchCommodity(goods, userID);
resoponsCode = HttpMethod.getStatusCode(closeableHttpResponse);
Reporter.log("接口返回状态码为:" + resoponsCode);
Assert.assertEquals(200, resoponsCode);
responseString = EntityUtils.toString(closeableHttpResponse.getEntity());
//获取到的responseBody为List,从list获取商品信息:商品名称、商品编号
List<Map<String, String>> rest = JSONObject.parseObject("[" + responseString + "]", List.class);
Map<String, String> commodmap = rest.get(0);//商品属性信息
String commdName = commodmap.get("commdName");//商品名称
String commdNum = commodmap.get("commdName");//商品编号
//提交订单
closeableHttpResponse = confirmOrder(commdName, commdNum, userID);
resoponsCode = HttpMethod.getStatusCode(closeableHttpResponse);
Reporter.log("接口返回状态码为:" + resoponsCode);
Assert.assertEquals(200, resoponsCode);
//付款
closeableHttpResponse = alipay(userID,payPassword);
resoponsCode = HttpMethod.getStatusCode(closeableHttpResponse);
Reporter.log("接口返回状态码为:" + resoponsCode);
Assert.assertEquals(200, resoponsCode);
responseString = EntityUtils.toString(closeableHttpResponse.getEntity());
//检查付款后的状态
Map<String,Map<String,List<Map<String,String>>>> payInfos = JSONObject.parseObject(responseString,Map.class);
Map<String,List<Map<String,String>>> infos = payInfos.get("info");
List<Map<String,String>> product = infos.get("product");
Map<String,String> payStatus = product.get(0);
String mesaage = payStatus.get("message");
if (mesaage.equals("支付成功")) {
Reporter.log("付款成功");
} else {
Assert.fail("付款失败");
}
}
//登录接口
//付款接口
public static CloseableHttpResponse alipay(String userID,String payPassword) throws Exception {
String baseURL = String.format("https://cashieret2.alipay.com/standard/securityAjaxValidate.json");
String sendCountv = "3";
String dataId = "1630738878667";
String dataSize = "1";
String dataIndex = "0";
Map<String,Map<String,Object>> dataContents = new HashMap<>();
Map<String,Object> payment_passwords = new HashMap<>();
payment_passwords.put("J_aliedit_key_hidn","payPassword");
payment_passwords.put("J_aliedit_uid_hidn","alieditUid");
payment_passwords.put("J_aliedit_using",true);
payment_passwords.put("payPassword",payPassword);
payment_passwords.put("alieditUid",userID);
payment_passwords.put("ks","");
payment_passwords.put("security_activeX_enabled",false);
dataContents.put("dataContent",payment_passwords);
String dataContent = null;
String callback = "light.packetRequest._packetCallbacks.callback2";
String securityId = "web|cashier_payment_3|b8942843-3e95-4d8d-95d1-b481e890c744RZ42";
String orderId = "090449ecdd982d023942014265143940";
setParamList("sendCountv",sendCountv);
setParamList("dataId",dataId);
setParamList("dataSize",dataSize);
setParamList("dataIndex",dataIndex);
setParamList("dataContent",dataContents.toString());
setParamList("dataContent",dataContent);
setParamList("callback",callback);
setParamList("securityId",securityId);
setParamList("orderId",orderId);
String getFixURl = stringBuilder.toString();
String destURL;
if (getFixURl.equals("")) {
destURL = baseURL;
} else {
destURL = String.format("%s?%s", baseURL, getFixURl);
}
CloseableHttpResponse closeableHttpResponse = HttpMethod.get(destURL);
int resoponsCode = HttpMethod.getStatusCode(closeableHttpResponse);
if (resoponsCode != 200) {
Assert.fail("接口返回值为" + resoponsCode);
} else {
Reporter.log("接口返回状态码为:" + resoponsCode);
}
return null;
}
//提交订单接口 post方法
public static CloseableHttpResponse confirmOrder(String goods, String num, String userID) throws Exception {
String baseURL = String.format("https://buy.tmall.com/order/confirm_order.html");
String xitemid = "";
String xuid = "";
setParamList("x-itemid", xitemid);
setParamList("xuid", xuid);
String getFixURl = stringBuilder.toString();
String destURL;
if (getFixURl.equals("")) {
destURL = baseURL;
} else {
destURL = String.format("%s?%s", baseURL, getFixURl);
}
//添加requestHeader
Map<String, String> reqHeaders = new HashMap<>();
reqHeaders.put(":authority", "buy.tmall.com");
reqHeaders.put("content-type:", "application/x-www-form-urlencoded");
reqHeaders.put("referer", "https://buy.tmall.com/order/confirm_order.htm?x-itemid=569619207456&x-uid=2248872497");
reqHeaders.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36");
//添加requestHeader中的cookie
Map<String, String> cookieInfos = new HashMap<>();
cookieInfos.put("_tb_token_", "e58ea8393654e");
cookieInfos.put("mt", "ci=0_1");
cookieInfos.put("cookie1", "UU6hQyKMZU4jXDBGqFTJwFIqH24CaAB%2BA%2FgoUIvCVtc%3D");
cookieInfos.put("cookie17", "UUplaX1NU55Spw%3D%3D");
cookieInfos.put("cancelledSubSites", "empty");
cookieInfos.put("existShop", "MTYzMDY3MTMxNg%3D%3D");
cookieInfos.put("unb", "2248872497");
cookieInfos.put("cna", "z18PF79S2gUCAXdivdnXsW5+");
reqHeaders.put("cookie", cookieInfos.toString());
//ajax发送的请求显示在request payload下面,而使用$.post方法发送的请求显示在form data下面
Map<String, String> formDatapost = confirmOrderFormData(goods, num, userID);
CloseableHttpResponse closeableHttpResponse = HttpMethod.postForm(destURL, formDatapost, reqHeaders);
int resoponsCode = HttpMethod.getStatusCode(closeableHttpResponse);
if (resoponsCode != 200) {
Assert.fail("接口返回值为" + resoponsCode);
} else {
Reporter.log("接口返回状态码为:" + resoponsCode);
}
return null;
}
//搜索商品接口 get接口 返回值为 respon
public static CloseableHttpResponse searchCommodity(String key, String pid) throws Exception {//
String baseURL = String.format("https://ai.taobao.com/search/index.htm");
stringBuilder = new StringBuilder();
//从搜索栏搜索水杯,将parmars加入url中
String spm = "a2e1u.19484427.search.1";
String union_lens = "recoveryid:201_11.15.254.94_2991001_1630590114625;prepvid:201_11.27.89.99_2990079_1630590143399";
setParamList("spm", spm);
setParamList("key", key);
setParamList("pid", pid);
setParamList("union_lens", union_lens);
String getFixURl = stringBuilder.toString();
String destURL;
if (getFixURl.equals("")) {
destURL = baseURL;
} else {
destURL = String.format("%s?%s", baseURL, getFixURl);
}
CloseableHttpResponse closeableHttpResponse = HttpMethod.get(destURL);
//获取 响应体
String reponsseString = EntityUtils.toString(closeableHttpResponse.getEntity());
//获取状态码
int resoponsCode = HttpMethod.getStatusCode(closeableHttpResponse);
if (resoponsCode != 200) {
Assert.fail("接口返回值为" + resoponsCode);
} else {
Reporter.log("接口返回状态码为:" + resoponsCode);
}
return closeableHttpResponse;
}
//淘宝登录接口 login.taobao.com psot方法
public static CloseableHttpResponse loginTaobao(String baseURL,String userID,String passWd) throws Exception {
stringBuilder = new StringBuilder();
String appName = "taobao";
String fromSite = "0";
String bx_v = "2.0.31";
setParamList("spm", appName);
setParamList("_bx-v", bx_v);
setParamList("fromSite-v", fromSite);
String getFixURl = stringBuilder.toString();
String destURL;
if (getFixURl.equals("")) {
destURL = baseURL;
} else {
destURL = String.format("%s?%s", baseURL, getFixURl);
}
Map<String,String> formData = loginHtmlFormData(userID,passWd);
CloseableHttpResponse closeableHttpResponse = HttpMethod.postForm(destURL,formData,null);
//获取状态码
int resoponsCode = HttpMethod.getStatusCode(closeableHttpResponse);
if (resoponsCode != 200) {
Assert.fail("接口返回值为" + resoponsCode);
} else {
Reporter.log("接口返回状态码为:" + resoponsCode);
}
return closeableHttpResponse;
}
private static StringBuilder stringBuilder;
//拼接URL
private static void setParamList(String key, String value) throws Exception {
if (key != null) {
stringBuilder.append("&");
stringBuilder.append(key);
stringBuilder.append("=");
stringBuilder.append(URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%3"));
}
}
public static Map<String,String> loginHtmlFormData(String loginID,String passWord){
Map<String,String> formData = new HashMap<>();
formData.put("loginId",loginID);
formData.put("password2", passWord);
formData.put("keepLogin","false");
formData.put("ua","ua");
formData.put("umidGetStatusVal","255");
formData.put("screenPixel","1536x864");
formData.put("navlanguage","zh-CN");
formData.put("navUserAgent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36");
formData.put("navPlatform","win32");
formData.put("appName","taobao");
formData.put("appEntrance","taobao_pc");
formData.put("_csrf_token","BHDwmZnnhyZUNtamQqqxr");
formData.put("umidToken","91a849abd6fc416d7286f2aaf26ee42fce91bc88");
formData.put("hsiz","1570a0a25005812aa6b0e7feb10a5b1f");
formData.put("bizParams","");
formData.put("style","default");
formData.put("appkey","00000000");
formData.put("from","tbTop");
formData.put("isMobile","false");
formData.put("lang","zh_CN");
formData.put("returnUrl","https://ai.taobao.com/?pid=mm_130402922_1111150093_109787700299&union_lens=lensId%3APUB%401627031547%40210803d1_0a2a_17ad2a32d65_05ec%4001");
formData.put("fromSite","");
formData.put("bx-ua","");
formData.put("bx-umidtoken","T2gADy-Z57QEyxwQH8Zff0muFwENP2YKN5uQTWoM0ex0OgFXRh0jpU9ESr5e-Fygd8w=");
return formData;
}
public static Map<String, String> confirmOrderFormData(String goods, String num, String userID) {
Map<String, String> postJson = new HashMap<>();
postJson.put("title", goods);
postJson.put("x_id", userID);
postJson.put("seller_id", "e12062f4a80b38680766f66e8acc2c6");
postJson.put("seller_nickname", "");
postJson.put("who_pay_ship", "");
postJson.put("photo_url", "");
postJson.put("region", "");
postJson.put("auto_post", "post");
postJson.put("etm", "");
postJson.put("virtual", "false");
postJson.put("rootCatId", "122952001");
postJson.put("auto_post1", "");
postJson.put("buyer_from", "ecity");
postJson.put("root_refer", "");
postJson.put("item_url_refer", "https%3A%2F%2Fuland.taobao.com%2F");
postJson.put("allow_quantity", "6683");
postJson.put("buy_param", num);
postJson.put("quantity", "1");
postJson.put("use_cod", "false");
postJson.put("_tb_token_", "ea7d355a4eeee");
postJson.put("skuInfo", "");
postJson.put("_input_charset", "UTF-8");
postJson.put("destination", "3333");
postJson.put("skuId", "33322");
postJson.put("bankfrom", "");
postJson.put("from_etao", "");
postJson.put("item_id_num", "");
postJson.put("item_id", "");
postJson.put("auction_id", "");
postJson.put("seller_rank", "");
postJson.put("seller_rate_sum", "");
postJson.put("is_orginal", "");
postJson.put("point_price", "false");
postJson.put("secure_pay", "");
postJson.put("pay_method", "");
postJson.put("from", "item_detail");
postJson.put("buy_now", "139");
postJson.put("current_price", "139");
postJson.put("auction_type", "b");
postJson.put("seller_num_id", "402379736");
postJson.put("activity", "");
postJson.put("chargeTypeId", "");
return postJson;
}
}