java 通过接口在后台管理器中生成数据
需求:测试人员在后台批量添加数据很麻烦,特别是针对一款商品配置了英语,还需要手动添加法语、俄语、阿拉伯语,很麻烦,但是因为没有项目组配合,做个小工具批量生成数据就只有自己去研究了
第一步:通过抓包工具fiddler查看接口走向
第二步:模拟url,进行请求
第三步:验证结果
第一步:从接口中我了解到,我们需要获取原始语言的数据,如:标题、名称、文件标题、详细信息,在把数据取出来,取出来后,在调用商品增加的接口,把数据内容填充进去,进行提交,就完了
目前我们排除登录态的问题,默认是可以登录成功的,因为默认我把cookie和session,是放在请求里面的,查看增加语言的接口
通过浏览器直接打开,数据是这样
模拟增加商品接口为,数据内容为
了解过程
代码实现逻辑
模拟浏览器的get和post请求,并把get和post请求返回的数据转换成map,封装的一个方法
package rosewholesale; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map; import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie; public class htppResopnes { public static Cookie staging = null;
public static Cookie ORIGINDC = null; public static final int[] successCode = { 200, 201, 202,302}; // 请求成功返回码 /**
* 向指定URL发送GET方法的请求
* @param url 发送请求的URL
* @return Result 所代表远程资源的响应,头信息
*
*/
public static Map<String, String> get(String url) {
Cookie staging = null;
//Cookie ORIGINDC = null;
int defaultConnectTimeOut = 30000; // 默认连接超时,毫秒
int defaultReadTimeOut = 30000; // 默认读取超时,毫秒 Map<String, String> result = new HashMap<String, String>();
BufferedReader in = null; try {
/* CookieManager manager=new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);*/
// 打开和URL之间的连接
URLConnection connection = new URL(url).openConnection();
// 此处的URLConnection对象实际上是根据URL的请求协议(此处是http)生成的URLConnection类的子类HttpURLConnection
// 故此处最好将其转化为HttpURLConnection类型的对象,以便用到HttpURLConnection更多的API.
HttpURLConnection httpURLConnection = (HttpURLConnection) connection; // 设置通用的请求属性
httpURLConnection.setRequestProperty("accept", "*/*");
httpURLConnection.setRequestProperty("connection", "Keep-Alive");
httpURLConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); httpURLConnection.setConnectTimeout(defaultConnectTimeOut);
httpURLConnection.setReadTimeout(defaultReadTimeOut); /*if (staging != null) {
httpURLConnection.setRequestProperty("Cookie", staging.toString());
}
if (ORIGINDC != null) {
httpURLConnection.setRequestProperty("Cookie", ORIGINDC.toString());
ORIGINDC = null;
}*/
// 建立连接
httpURLConnection.connect();
/* CookieStore cookieJar = (CookieStore) manager.getCookieStore();*/
result = getResponse(httpURLConnection, in, result); } catch (Exception requestException) {
System.err.println("发送GET请求出现异常!" + requestException);
// requestException.printStackTrace();
}
// 关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception closeException) {
closeException.printStackTrace();
}
} return result;
} /**
* 向指定URL发送GET方法的请求,并携带指定cookie
* @param url 发送请求的URL
* @param cookies 请求时携带的cookie
* @return Result 所代表远程资源的响应,头信息
*
*/
public static Map<String, String> get(String url,String cookies) {
Cookie staging = null;
//Cookie ORIGINDC = null;
int defaultConnectTimeOut = 50000; // 默认连接超时,毫秒
int defaultReadTimeOut = 50000; // 默认读取超时,毫秒 Map<String, String> result = new HashMap<String, String>();
BufferedReader in = null; try {
// 打开和URL之间的连接
URLConnection connection = new URL(url).openConnection();
// 此处的URLConnection对象实际上是根据URL的请求协议(此处是http)生成的URLConnection类的子类HttpURLConnection
// 故此处最好将其转化为HttpURLConnection类型的对象,以便用到HttpURLConnection更多的API.
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
// 设置通用的请求属性
httpURLConnection.setRequestProperty("accept", "*/*");
httpURLConnection.setRequestProperty("connection", "Keep-Alive");
httpURLConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
httpURLConnection.setRequestProperty("Cookie", "Cookie: LPVID=NiNTJlMDdhOWIxMTM0N2Zm; cookieid=10023149924547802009973797079868836; scarab.visitor=%2231990FE0AA92EF1D%22; cookie_lang=en; bizhong=USD; _ga=GA1.2.2047632407.1495188930; first_access=yes; rosegal_us=visit; rosegal_caen=visit; RG_SESSIONID="+cookies+"; expandable=0c");
httpURLConnection.setConnectTimeout(defaultConnectTimeOut);
httpURLConnection.setReadTimeout(defaultReadTimeOut);
// 建立连接
httpURLConnection.connect();
result = getResponse(httpURLConnection, in, result); } catch (Exception requestException) {
System.err.println("发送GET请求出现异常!" + requestException);
// requestException.printStackTrace();
}
// 关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception closeException) {
closeException.printStackTrace();
}
} return result;
} /**
* 根据返回码处理返回值
* @param httpURLConnection
* @param in
* @param result
* @return
* @throws UnsupportedEncodingException
* @throws IOException
*/
public static Map<String, String> getResponse(HttpURLConnection httpURLConnection, BufferedReader in, Map<String, String> result)
throws UnsupportedEncodingException, IOException {
int contentLengthAllow = -1; // 返回报文长度限制, 为-1时不限制长度 boolean flag = false;
for (int i = 0; i < successCode.length; i++) {
if (successCode[i] == httpURLConnection.getResponseCode()) {
flag = true;
break;
}
} // 返回码非“successCode”时,response为返回message
if (flag) {
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
String line; // 获取所有响应头字段
Map<String, List<String>> Hearder = httpURLConnection.getHeaderFields();
for (String key : Hearder.keySet()) {
result.put(key, Hearder.get(key).toString());
} // responseList.clear();
String responseStr = "";
while ((line = in.readLine()) != null) {
responseStr += line;
} // Content长度限制
if (responseStr.length() > contentLengthAllow && contentLengthAllow > 0) {
responseStr = responseStr.substring(0, contentLengthAllow);
} result.put("Message", httpURLConnection.getResponseMessage());
result.put("Code", String.valueOf(httpURLConnection.getResponseCode()));
result.put("Response", responseStr);
} else {
result.put("Message", httpURLConnection.getResponseMessage());
result.put("Code", String.valueOf(httpURLConnection.getResponseCode()));
//
result.put("Response", httpURLConnection.getResponseMessage());
// 获取所有响应头字段
Map<String, List<String>> Hearder = httpURLConnection.getHeaderFields();
for (String key : Hearder.keySet()) {
result.put(key, Hearder.get(key).toString());
}
}
return result;
} /**
* 发送post请求,并带上cookie
* @param reqData:请求参数,reqUrl:请求url,cookies:请求cookie
* @throws IOException
* @return String
*/
public static String sentPost(String reqData, String reqUrl, String cookies) throws IOException { URL url;
url = new URL(reqUrl);
URLConnection connection = url.openConnection();
connection.setRequestProperty("Cookie", cookies);
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "GBK");
out.write(reqData); // 向页面传递数据。post的关键所在!
out.flush();
out.close();
// 一旦发送成功,用以下方法就可以得到服务器的回应:
String sCurrentLine;
String sTotalString;
sCurrentLine = "";
sTotalString = "";
InputStream l_urlStream;
l_urlStream = connection.getInputStream();
// 传说中的三层包装阿!
BufferedReader l_reader = new BufferedReader(new InputStreamReader(l_urlStream));
while ((sCurrentLine = l_reader.readLine()) != null) {
sTotalString += sCurrentLine + "\r\n";
}
return sTotalString;
} /**
* 获取请求的cookie
* @return String
* @param url:请求的url
* 创建时间:2017-03-04,最后更新时间:2017-03-04
*/
public static String getCookie(String url) { int defaultConnectTimeOut = 30000; // 默认连接超时,毫秒
int defaultReadTimeOut = 30000; // 默认读取超时,毫秒
String CookieStr = ""; BufferedReader in = null;
try {
URLConnection connection = new URL(url).openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) connection; httpURLConnection.setRequestProperty("accept", "*/*");
httpURLConnection.setRequestProperty("connection", "Keep-Alive");
httpURLConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
httpURLConnection.setConnectTimeout(defaultConnectTimeOut);
httpURLConnection.setReadTimeout(defaultReadTimeOut);
if (staging != null) {
httpURLConnection.setRequestProperty("Cookie", staging.toString());
}
if (ORIGINDC != null) {
httpURLConnection.setRequestProperty("Cookie", ORIGINDC.toString());
ORIGINDC = null;
} // 建立连接
httpURLConnection.connect(); // 从请求中获取cookie列表
String cookieskey = "Set-Cookie";
Map<String, List<String>> maps = httpURLConnection.getHeaderFields();
List<String> coolist = maps.get(cookieskey);
Iterator<String> it = coolist.iterator();
StringBuffer sbu = new StringBuffer();
// 拼接cookie再请求
sbu.append("eos_style_cookie=default; ");
while (it.hasNext()) {
sbu.append(it.next() + ";");
}
CookieStr = sbu.toString();
CookieStr = CookieStr.substring(0, CookieStr.length() - 1);
System.out.println("**************CookieStr:" + CookieStr);
} catch (Exception requestException) {
System.err.println("发送GET请求出现异常!" + requestException);
}
// 关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception closeException) {
closeException.printStackTrace();
}
}
return CookieStr;
} }
请求数据内容
第一步:请求原始数据,
String url = "http://xxx.com.trunk.s1.egomsl.com/eload_admin/goods.php?act=edit&goods_id=140861765";// 取出sku
System.out.println("请求的接口地址为:" + url);
Map<String, String> getUrl = htppResopnes.get(url, cookies);
String resopnes = getUrl.get("Response");
打印出来的response,就是一个标准的html文件
第二步:获取原始语言
使用Jsoup这个jar包可以把html的文件给读取出来,后续我在整理下jsoup的几种方式
Document doc = Jsoup.parse(resopnes); // 使用jsoup 进行语言转换
String getTitle = doc.select("#goods_title").attr("value");// 商品标题
String getProductName = doc.select("#showtab0 > tbody > tr:nth-child(2) > td:nth-child(2) > input.input_style").attr("value");// 商品名称
String getFileTile = doc.select("#auto_thumb_3 > input[type='text']").attr("value");// 静态页面文件标题
String detail = doc.select("#goods_desc_en").text();// 详细描述
System.out.println("商品标题"+getTitle);
System.out.println("商品名称"+getProductName);
System.out.println("静态页面文件标题"+getFileTile);
System.out.println("详细描述"+detail);
打印效果
第三步:增加商品数据,post请求数据
POST提交增加数据,唯一关注的是要带上cookie,因为现在是需要带上cookie才默认是登录状态
public static void setlanguage(String string,String getTitle,String getFileTile ,String getProductName,String getDetail,String language,String cookies){
//请求的post
String reqUrl="http://rosegal.com.trunk.s1.egomsl.com/eload_admin/goods.php?act=add_save";
String reqData="goods_id="+string+"&goods_title="+language+"-"+getTitle
+ "&url_title="+language+"1-"+getProductName+"&goods_name="+language+"-"+getFileTile+"&language="+language+"&goods_desc="+getDetail;
String setcookies="Cookie: LPVID=NiNTJlMDdhOWIxMTM0N2Zm; cookieid=10023149924547802009973797079868836; scarab.visitor=%2231990FE0AA92EF1D%22; cookie_lang=en; bizhong=USD; first_access=yes; rosegal_us=visit; rosegal_caen=visit; _ga=GA1.2.2047632407.1495188930; _gid=GA1.2.1248057120.1504233472; RG_SESSIONID="+cookies+"; WEB[last_choose]=210"; try {
String posts=htppResopnes.sentPost(reqData, reqUrl, setcookies).trim();
System.out.println("添加多语言:"+language+posts);
} catch (IOException e) {
e.printStackTrace();
}
}
部分实现全部的代码
String url = "http://rosegal.com.trunk.s1.egomsl.com/eload_admin/goods.php?act=edit&goods_id=140861765";// 取出sku
// 获取的url为
System.out.println("请求的接口地址为:" + url);
Map<String, String> getUrl = htppResopnes.get(url, cookies);
String resopnes = getUrl.get("Response");
System.out.println(resopnes); Document doc = Jsoup.parse(resopnes); // 使用jsoup 进行语言转换
String getTitle = doc.select("#goods_title").attr("value");// 商品标题
String getProductName = doc.select("#showtab0 > tbody > tr:nth-child(2) > td:nth-child(2) > input.input_style").attr("value");// 商品名称
String getFileTile = doc.select("#auto_thumb_3 > input[type='text']").attr("value");// 静态页面文件标题
String detail = doc.select("#goods_desc_en").text();// 详细描述 System.out.println("商品标题"+getTitle);
System.out.println("商品名称"+getProductName);
System.out.println("静态页面文件标题"+getFileTile);
System.out.println("详细描述"+detail); setlanguage(goodsid, getTitle, getProductName, getFileTile, detail, "fr", cookies);// 法语
setlanguage(goodsid, getTitle, getProductName, getFileTile, detail, "ru", cookies);// 俄语
setlanguage(goodsid, getTitle, getProductName, getFileTile, detail, "ar", cookies);// 阿拉伯语
效果
在界面上其他语言已经添加成功
剩下事就是把生成可执行的jar文件,写个bat文件,拿给其他人执行
java 通过接口在后台管理器中生成数据的更多相关文章
- JAVA学习Swing章节流布局管理器简单学习
package com.swing; import java.awt.Container; import java.awt.FlowLayout; import javax.swing.JButton ...
- f2fs解析(八)node 管理器中的node_info
free_info 功成身退,node_info顺利接班. // 这里还是蛮复杂的一件事,如果不搞清除的话,这个历史性的接班工作我们就接不上 上面说到 alloc_nid 和 alloc_nid_do ...
- 如何在URL筛选管理器中过滤不需要的URL
互联网可以说是一把名副其实的双刃剑.一方面其可以提高工作效率.给企业提供充分的资源;另一方面如果管理不严,也会带来很多的隐患.如员工在上班时间玩游戏.炒股等等.为此现在很多企业希望对员工的网络行为进行 ...
- (转)Java 的swing.GroupLayout布局管理器的使用方法和实例
摘自http://www.cnblogs.com/lionden/archive/2012/12/11/grouplayout.html (转)Java 的swing.GroupLayout布局管理器 ...
- f2fs解析(七)node管理器中的 free_nid 结构体
除了node_info之外, node管理器中还有还有个重要的数据结构: struct free_nid { struct list_head list; /* for free node id li ...
- 无法将从VSS中的解决方案添加到TFS的源代码管理器中
VSS是一种非常有用的项目文件管理工具,百度百科的解释是:VSS 的全称为 Visual Source Safe .作为 Microsoft Visual Studio 的一名成员,它主要任务就是负责 ...
- 元数据管理器中存在错误。 实例化来自文件“\\?\C:\Program Files\Microsoft SQL Server\MSAS11.MSSQLSERVER\OLAP\Data\Tfs_Analysis.0.db\vDimTestCaseOverlay.874.dim.xml”的元数据对象时出错。
一.发现问题 启动SQLSERVER的数据分析服务失败 查看系统日志错误如下: 双击错误后显示详细错误: 元数据管理器中存在错误. 实例化来自文件“\\?\C:\Program Files\Micro ...
- Visual studio2019配置OPENCV 时属性管理器中没有Microsoft.Cpp.x64.user的解决办法
方法一:重新下载Visual studio2017,再次打开2019就会出现Microsoft.Cpp.x64.user,感觉有些麻烦,也占电脑空间,推荐方法二. 方法二:与方法一原理相同,下载201 ...
- 解决SpringMVC拦截器中Request数据只能读取一次的问题
解决SpringMVC拦截器中Request数据只能读取一次的问题 开发项目中,经常会直接在request中取数据,如Json数据,也经常用到@RequestBody注解,也可以直接通过request ...
随机推荐
- wireshark开发环境搭建
自己完成了wireshark开发环境的搭建,主要参考资料是wireshark的官方developer-guide.pdf,网址:https://www.wireshark.org/docs/. 现把搭 ...
- Dev Express Report 学习总结(四)Dev Express 动态生成XRTable使用总结
1. XRTableCell常见属性 XRTableCell xrTableCell = new XRTableCell(); A. 字体及字体大小 xrTableCell.Font = new S ...
- caffe学习资料
1.利用Caffe做回归(regression) http://www.cnblogs.com/frombeijingwithlove/p/5314042.html
- Cinder Columns
http://www.screencast.com/users/xiangxinyong/folders/Smaug http://www.screencast.com/t/SLqCyOwtBRl
- 牛客网Java刷题知识点之File对象常用功能:获取文件名称、获取文件路径、获取文件大小、获取文件修改时间、创建与删除、判断、重命名、查看系统根目录、容量获取、获取某个目录下内容、过滤器
不多说,直接上干货! 获取文件名称.获取文件路径.获取文件大小.获取文件修改时间 FileMethodDemo.java package zhouls.bigdata.DataFeatureSelec ...
- C语言实现通用链表初步(一)
注意:本文讨论的是无头单向非循环链表. 假设不采用Linux内核链表的思路,怎样用C语言实现通用链表呢? 一种常用的做法是: typedef int element_t; struct node_in ...
- httpd编译安装php
wget http://hk1.php.net/distributions/php-5.6.31.tar.gz yum groupinstall "Development Tools&quo ...
- JavaScript判断变量类型
使用JavaScript变量时是无法判断出一个变量是0 还是“”的 这时可用typeof()来判断变量是string 还是number来区分0和“”, typeof(undefined) == 'un ...
- 2019.3.26判断是否回文(java实现)
我所有的文章都是对我总结学习的总结,那里不好或者冒犯了那里,我先对您说声对不起,请告知我进行改正. 今天java老师作业题目是判断是一个字符串否是回文: emmmm,我的思路是将字符串逆序,然后使用方 ...
- TP5.0搭建restful API 应用
1.配置环境变量,如果没配置会显示如下错误. 配置方法 1)右键此电脑-> 属性-> 高级系统设置->环境变量->Path 2)在Path后加上php目录的名称 如:E:\PH ...