Commit 5d10177a by Li Yongyu

lyy add

parent fa613b0a
package Practice_test;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
public class CanshuTiQu {
public static void main(String[] args) {
String str="\"phone\":\"13910960649\",\"thirdSource\":\"GM\",\"thirdSourceId\":\"ys\",\"verifyCode\":code_own\"";
String a=getAll(str,"verifyCode");
System.out.println("a="+a);
}
// 在parameter中查看,是否有(第二个参数)verifyCode的关键字,有的话返回他的字母值
public static String getAll(String parameter, String Letter) {
String[] strcomma = parameter.split(",");
int comma = strcomma.length;
StringBuffer sb = new StringBuffer();
for (int k = 0; k < comma; k++) {
// 此时是多个,,,
String[] str = strcomma[k].split(":");
String str_strcomma = Arrays.toString(str);
// System.out.println("str="+Arrays.toString(str));
// 按参数传过来的字符串做为子串,在以逗号为节点的串中分别查找子串的关键字,
// 在找到后的位置开始查找数字,最后把数字的字符串返回
if (str_strcomma.contains(Letter)) {
int start = str_strcomma.indexOf(',');
sb.append(str_strcomma.substring(start + 2,
str_strcomma.length() - 1));
}
}
return sb.toString();
}
}
package Practice_test;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class HttpUtils {
/**
* get
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doGet(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
/**
* post form
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
/**
* Post String
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Post stream
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Put String
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Put stream
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Delete
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doDelete(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (!StringUtils.isBlank(path)) {
sbUrl.append(path);
}
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}
return sbUrl.toString();
}
private static HttpClient wrapClient(String host) {
HttpClient httpClient = new DefaultHttpClient();
if (host.startsWith("https://")) {
sslClient(httpClient);
}
return httpClient;
}
private static void sslClient(HttpClient httpClient) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry registry = ccm.getSchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
}
\ No newline at end of file
package Practice_test;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class HttpsUtil_Post_Json {
private static class TrustAnyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}
private static class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
/**
* post��ʽ���������(httpsЭ��) ����json����
*
* @param url
* �����ַ
* @param content
* ����
* @param charset
* ����
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
*/
public static void main(String[] args) {
try {
post("https://api.puhuifinance.com/datapi-blacklist-server/api/v1/batchQueryBlacklist/query",
"[{\"queryField\":\"id_no\",\"queryValue\":\"13910960649\"}]",
"utf-8");
} catch (KeyManagementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static byte[] post(String url, String content, String charset)
throws NoSuchAlgorithmException, KeyManagementException,
IOException {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
new java.security.SecureRandom());
URL console = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setRequestProperty("Content-Type","application/json");
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.setDoOutput(true);
conn.connect();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(content.getBytes(charset));
// ˢ�¡��ر�
out.flush();
out.close();
InputStream is = conn.getInputStream();
if (is != null) {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
return outStream.toByteArray();
}
return null;
}
}
\ No newline at end of file
package Practice_test;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class LMFMD5 {
//创建一个类LMFMD5
public String MD5(String sourceStr) {
String result = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
// 生成一个MD5加密计算摘要
md.update(sourceStr.getBytes());
// 使用指定的byte数组更新摘要
byte b[] = md.digest();
// 把密文转换成十六进制的字符串形式
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
result = buf.toString();
System.out.println("MD5(" + sourceStr + ",32) = " + result);
// System.out.println("MD5(" + sourceStr + ",16) = " + buf.toString().substring(8, 24));
// 注释的是md5的16位取值
} catch (NoSuchAlgorithmException e) {
System.out.println(e);
}
return result;
}
}
package Practice_test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.offcn.TestUnti.ReadProperties;
public class MySqlUtil {
public static String sql;
public static Connection conn =null;
public static Statement stmt=null;
public static ResultSet result = null;
public static void main(String[] args) {
//update xyu.xyu_room set status=4 where room_num=201808310045;
// int a=updateOrderStatus("xyu.xyu_room","status=4", "room_num=201808310045");
// System.out.println(a);
select( " xyu_room " , " room_name = '中国特长房间名' ");
}
public static void closed(){
try {
result.close();
stmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void select(String tableName, String condition){
//数据库连接
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://192.168.10.222:3306/xyu?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull","root"
,"offcn.com");
// Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.10.222:3306/xyu?user=root&amp;password=offcn.com&amp;useUnicode=true&amp;characterEncoding=UTF8");
stmt = conn.createStatement();
// sql = "select * from " + " xyu_users;" ;
sql = "select * from " + tableName + " where " + condition;
System.out.println(sql);
// System.out.println("select_sql="+sql);
result = stmt.executeQuery(sql);
result.last();
System.out.println(result.getRow());
if (result.getRow() != 1) {
System.out.println(result.getRow());
} else{
// String act_idNo = String.valueOf(result.getString(result.findColumn("mobile")));
// System.out.println("name:"+act_idNo);
// String act_idNo = String.valueOf(rs_cust_info.getString(rs_cust_info.findColumn("id_no")));
}
} catch (Exception e) {
e.printStackTrace();
}finally{
closed();
}
}
//更改表
public static Integer updateOrderStatus(String fromName,String setCondition, String whereCondition) {
Integer result1=null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://192.168.10.222:3306/xyu","root"
,"offcn.com");
// Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.10.222:3306/xyu?user=root&amp;password=offcn.com&amp;useUnicode=true&amp;characterEncoding=UTF8");
stmt = conn.createStatement();
String sql = "update "+ fromName +" set "+ setCondition +" where "+ whereCondition;
System.out.println(sql);
result1 = stmt.executeUpdate(sql);//
if (result1 == -1) {
System.out.println("update order states failed!");
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("update order states failed!");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}try {
stmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result1;
}
}
package Practice_test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Encoder;
public class OCRTest {
public static String request(String httpUrl, String httpArg) {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// 填入apikey到HTTP header
connection.setRequestProperty("apikey", "42d199bc0a50cd8e109ff880ecc444fe");
connection.setDoOutput(true);
connection.getOutputStream().write(httpArg.getBytes("UTF-8"));
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
// <pre name="code" class="java">
/**
* @param args
*/
public static void main(String[] args) {
File file = new File("d:\\abc.jpg");
String imageBase = OCRTest.encodeImgageToBase64(file);
imageBase = imageBase.replaceAll("\r\n","");
imageBase = imageBase.replaceAll("\\+","%2B");
String httpUrl = "http://apis.baidu.com/apistore/idlocr/ocr";
String httpArg = "fromdevice=pc&clientip=10.10.10.0&detecttype=LocateRecognize&languagetype=CHN_ENG&imagetype=1&image="+imageBase;
String jsonResult = request(httpUrl, httpArg);
System.out.println("返回的结果--------->"+jsonResult);
}
// //Base64编解码
// private static String encodeTest(String str){
// Base64 base64 = new Base64();
// try {
// str = base64.encodeToString(str.getBytes("UTF-8"));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// System.out.println("Base64 编码后:"+str);
// return str;
// }
//
// private static void decodeTest(String str){
// Base64 base64 = new Base64();
// //str = Arrays.toString(Base64.decodeBase64(str));
// str = new String(Base64.decodeBase64(str));
// System.out.println("Base64 解码后:"+str);
// }
public static String encodeImgageToBase64(File imageFile) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
// 其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(imageFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);// 返回Base64编码过的字节数组字符串
}
}
\ No newline at end of file
package Practice_test;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import net.sf.json.JSONObject;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import com.offcn.TestUnti.Log;
public class ReadExcels {
private String fileName;
private String SheetName;
public ReadExcels() {
}
public ReadExcels(String fileName, String sheetName) {
this.fileName = fileName;
SheetName = sheetName;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getSheetName() {
return SheetName;
}
public void setSheetName(String sheetName) {
SheetName = sheetName;
}
@SuppressWarnings({ "unused", "resource" })
public Object[][] readExcels_return() throws Exception{
String targetFile = "TestData/"+fileName;
FileInputStream fis = new FileInputStream(new File(targetFile));
Workbook wb = WorkbookFactory.create(new File(targetFile));
Sheet sheet = wb.getSheet(SheetName);
int rows=sheet.getPhysicalNumberOfRows();
//有多少行数据就创建多少个map,首行是标题第二行开始才是数据,所以rows-1
@SuppressWarnings("unchecked")
HashMap<String, Object>[][] arrmap = new HashMap[rows-1][1];
List<String> list = new ArrayList<String>();
//每个子map分别为arrmap[0][0]、arrmap[1][0]、arrmap[2][0]。。。
for(int i = 1 ; i < sheet.getPhysicalNumberOfRows() ; i++){
arrmap[i-1][0] = new HashMap<>();
}
//获取标题行数据存放在list里面
for(int i = 0 ; i < 1 ; i++){
Row r = sheet.getRow(i);
for (int j = 0; j < r.getPhysicalNumberOfCells(); j++) {
Cell cell = r.getCell(j);
list.add(getCellValue(cell));
}
}
for(int i = 1 ; i < sheet.getPhysicalNumberOfRows() ; i++){
Row r = sheet.getRow(i);
for (int j = 0; j < r.getPhysicalNumberOfCells(); j++) {
Cell cell = r.getCell(j);
String brandName=getCellValue(cell);
//如果列名是parameter的时候,按逗号分隔字符串
if("parameter".equals(list.get(j))){
System.out.println("看看="+brandName);
arrmap[i - 1][0].put(list.get(j), brandName);//分别往每个子map中存放数据,每行是一个map
// String[] strcomma=brandName.split(",");
// int comma=strcomma.length;
// for(int k=0;k<comma;k++){
// String[] str=strcomma[k].split(":");
// System.out.println("str="+Arrays.toString(str));
// if(str.length>1){
// arrmap[i - 1][0].put((String)filterString(str[0].trim(),i,j),filter(str[1],i,j));//分别往每个子map中存放数据,每行是一个map
//// arrmap[i - 1][0].put((String)(str[0].trim()),(str[1]));//分别往每个子map中存放数据,每行是一个map
// }
// }
}else{
arrmap[i - 1][0].put(list.get(j), brandName);//分别往每个子map中存放数据,每行是一个map
}
}
}
/**
* 查看数据提取结果
for(int i=0;i<arrmap.length;i++){
for(int j=0;j<arrmap[i].length;j++){
System.out.print(" "+arrmap[i][j]);
}
System.out.println();
}
for(int i=0;i<arrmap.length;i++){
HashMap<String, Object> arr=arrmap[i][0];
System.out.println("处理后数据="+JSONObject.fromObject(arr).toString());
}
*/
System.out.println(arrmap);
return arrmap;
}
//去掉字符串的双引号,row行,j列
private String filterString(String str,int rows,int j){
if(str==null){
Log.logError("readExcels filterString error"+str+"发生在"+rows+"行"+j+"列");
return "null";
}
StringBuffer sb=new StringBuffer();
for(int i=0;i<str.length();i++){
char c=str.charAt(i);
if(str.charAt(i)=='"'){
}else{
sb.append(c);
}
}
return sb+"";
}
//输入类型转换成数字型,row行,j列
private Long filterInt(String str){
return Long.valueOf(str);
}
//选择何种转换方式
private Object filter(String str,int i,int j){
System.out.println(111);
System.out.println(str);
if(str.equals("null")){
System.out.println(1234);
return "null";
}
if(str.equals("\"null\"")){
System.out.println(5678);
return "\"null\"";
}
if(!Character.isDigit(str.charAt(0))){//如果首位不是数字就按字符串处理
return filterString(str, i, j);
}else{
// return filterInt(str);
return "";
}
}
private String getCellValue(Cell cell){
int cellType=0;
try {
cellType = cell.getCellType();
} catch (Exception e) {
return "无法解析";
}
String value = "";
if(cellType == Cell.CELL_TYPE_STRING){
value = cell.getStringCellValue();
}else if(cellType == Cell.CELL_TYPE_NUMERIC){
value = String.valueOf(cell.getNumericCellValue());
}else if(cellType == Cell.CELL_TYPE_BOOLEAN){
value = String.valueOf(cell.getBooleanCellValue());
}else if(cellType == Cell.CELL_TYPE_BLANK){
value = "";
}else if(cellType == Cell.CELL_TYPE_FORMULA){
value = String.valueOf(cell.getCellFormula());
}else{
value = "";
}
return value;
}
}
package Practice_test;
import static io.restassured.http.ContentType.JSON;
import java.io.File;
import java.util.HashMap;
import org.json.simple.JSONObject;
import io.restassured.RestAssured;
import io.restassured.config.RestAssuredConfig;
import io.restassured.config.SSLConfig;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.response.Response;
import io.restassured.path.json.JsonPath;
public class RequestDataUtils2 {
//发送post请求前的准备
private static RestAssured getRMEnv() {
RestAssured ra = new RestAssured();
ra.config = RestAssuredConfig.newConfig().sslConfig(
SSLConfig.sslConfig().allowAllHostnames());
ra.baseURI = "http://ut1.zuul.pub.puhuifinance.com";
ra.port = 8765;
ra.basePath = "/bestbuy-app-server-cloud-server/api";
return ra;
}
//发送post请求返回整个响应结果
public static Response getPostResponse() {
RequestDataUtils2 rdu=new RequestDataUtils2();
Response re=null;
String url="/v1/customer/photo/upload";
try{
File filen=new File("out/3.jpg");
re=rdu.getRMEnv().given()
.header("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJtYWMiOiIxNDk5NDMwNzQwNzQzIiwidXNlcklkIjoyMjQxMCwic3ViIjoiMTU4MTEwMDM0MzEiLCJpc3MiOiJybS1hcHAtc2VydmVyIiwiaWF0IjoxNTAwMzY5MDE4fQ.nixejoF9AJCnBnj7JUkP9kcROWW3qnpP_yKUydJ0i-U")
.multiPart("file", filen)
// .queryParam("orderId",map.get("orderId")+"&photoType="+map.get("photoType")+"&photoLocation="+map.get("photoLocation"))
// .pathParam("photoType",map.get("photoType"))
// .pathParam("photoLocation",map.get("photoLocation"))
.when()
.post(url+"?photoType=1&photoLocation=2&orderId=38858")
.thenReturn();
// File filen=new File("out/"+filename);
// re=rdu.getRMEnv(tem).given().header("Authorization", ZY.ZY_Token.get("token")==null? "":ZY.ZY_Token.get("token"))
// .when().multiPart("file", filen)
// .params(map)
// .post(serviceURL).andReturn();
}catch(Exception e){
System.out.println(e.getMessage());
// re=rdu.getRMEnv(tem).given().header("Authorization", ZY.ZY_Token.get("token")==null? "":ZY.ZY_Token.get("token"))
// .when()
// .params(map)
// .post(serviceURL).andReturn();
}
System.out.println(re.asString());
return null;
}
public static void main(String[] args) throws Exception {
getPostResponse();
}
}
package Practice_test;
import static io.restassured.http.ContentType.JSON;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.json.simple.JSONObject;
import io.restassured.RestAssured;
import io.restassured.config.RestAssuredConfig;
import io.restassured.config.SSLConfig;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.response.Response;
import io.restassured.path.json.JsonPath;
public class RequestDataUtils3 {
//发送post请求前的准备
private static RestAssured getRMEnv() {
RestAssured ra = new RestAssured();
ra.config = RestAssuredConfig.newConfig().sslConfig(
SSLConfig.sslConfig().allowAllHostnames());
// ra.baseURI = "http://ut1.zuul.pub.puhuifinance.com";
// ra.port = 8765;
// ra.basePath = "/bestbuy-app-server-cloud-server/api";
return ra;
}
//发送post请求返回整个响应结果
public static Response getPostResponse() {
RequestDataUtils3 rdu=new RequestDataUtils3();
Response re=null; //{}
String url="http://beta.alitest.eoffcn.com/admin/customer/getList?page=1&size=10&username=YS自动化测试&phone=13910960649&:;\\|-+)(*~`.?^%$#@{[]><,card_no=qty50636&status=1";
// String url="http://beta.alitest.eoffcn.com/admin/customer/getList?page=1&size=10&username=YS自动化测试&phone=13910960649&':;\\|-+)(*~`{}[]><,.?^%$#@!card_no=qty50636&status=1";
Map<String,String> m=new HashMap<String,String>();
m.put("user_name", "ws63417");
m.put("password", "ws63417");
m.put("code", "7bcdc063c9ed80c9f9fee83f1101aaed");
try{
// File filen=new File("out/3.jpg");
re=rdu.getRMEnv().given()
// .header("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJtYWMiOiIxNDk5NDMwNzQwNzQzIiwidXNlcklkIjoyMjQxMCwic3ViIjoiMTU4MTEwMDM0MzEiLCJpc3MiOiJybS1hcHAtc2VydmVyIiwiaWF0IjoxNTAwMzY5MDE4fQ.nixejoF9AJCnBnj7JUkP9kcROWW3qnpP_yKUydJ0i-U")
// .multiPart("file", filen)
// .queryParam("orderId",map.get("orderId")+"&photoType="+map.get("photoType")+"&photoLocation="+map.get("photoLocation"))
// .pathParam("photoType",map.get("photoType"))
// .pathParam("photoLocation",map.get("photoLocation"))
.cookie("PHPSESSID","7nm2u0efp5leta3quif37dm6r4")
.get(url)
.thenReturn();
// File filen=new File("out/"+filename);
// re=rdu.getRMEnv(tem).given().header("Authorization", ZY.ZY_Token.get("token")==null? "":ZY.ZY_Token.get("token"))
// .when().multiPart("file", filen)
// .params(map)
// .post(serviceURL).andReturn();
}catch(Exception e){
System.out.println(e.getMessage());
// re=rdu.getRMEnv(tem).given().header("Authorization", ZY.ZY_Token.get("token")==null? "":ZY.ZY_Token.get("token"))
// .when()
// .params(map)
// .post(serviceURL).andReturn();
}
System.out.println(re.asString());
return null;
}
public static void main(String[] args) throws Exception {
getPostResponse();
}
}
package Practice_test;
import static io.restassured.http.ContentType.JSON;
import java.util.List;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.response.Response;
/**
* 人工信审工具类
* @author puhui
*
*/
public class Rgxs{
// public String JSESSIONID;
// public String StatusCode;
// public String time;
public static void main(String[] args) {
Rgxs r=new Rgxs();
String JSESSIONID=r.getJSESSIONID();
r.login(JSESSIONID);
}
public String getJSESSIONID(){
String JSESSIONID;
String StatusCode;
String time;
RestAssured ra_VerifyCode = new RestAssured();
ra_VerifyCode.baseURI = "http://10.10.227.155";
ra_VerifyCode.port = 8092;
ra_VerifyCode.basePath = "/puhui-cas/login?service=http://10.10.180.37:9092/cas-login";
String s="username=guanxin&password=123456&captcha=&lt=LT-91693-umbYEtmZoAIwfMz6DgJ4TYyMEdJuon-inside.puhuifinance.com%2Fpuhui-cas&execution=e1s1&_eventId=submit";
Long start=System.currentTimeMillis();
Response re2 = ra_VerifyCode.given().given().get();
Long end=System.currentTimeMillis();
JSESSIONID=re2.getHeader("Set-Cookie").split(";")[0];
System.out.println(JSESSIONID);
return JSESSIONID;
}
public String login(String JSESSIONID){
//登陆http://10.10.227.155:8092/puhui-cas/login;jsessionid=CB6D5A088E0131A8D3DBB4C09CF537EB?service=http://10.10.180.37:9092/cas-login&locale=zh_CN
String StatusCode;
String time;
RestAssured ra_VerifyCode = new RestAssured();
ra_VerifyCode.baseURI = "http://10.10.227.155";
ra_VerifyCode.port = 8092;
ra_VerifyCode.basePath = "/puhui-cas/login;"+JSESSIONID+"?service=http://10.10.180.37:9092/cas-login&locale=zh_CN";
String Parameter="username=guanxin&password=123456&captcha=&lt=LT-95983-ZMh4JH2vw71sRMqERKcTOHGuiPDUtb-inside.puhuifinance.com%2Fpuhui-cas&execution=e1s1&_eventId=submit";
Long start=System.currentTimeMillis();
Response re2 = ra_VerifyCode.given().given().contentType(ContentType.URLENC).
headers("Cookie", JSESSIONID,
"Referer","http://10.10.227.155:8092/puhui-cas/login?service=http://10.10.180.37:9092/cas-login",
"Origin","http://10.10.227.155:8092"
).body(Parameter).when().post();
Long end=System.currentTimeMillis();
System.out.println("第二步完成");
System.out.println(re2.getHeaders().toString());
System.out.println(re2.getBody().asString());
System.out.print("名称:"+Thread.currentThread().getName()+"状态:"+re2.getStatusCode()+"耗时:毫秒");
return JSESSIONID;
}
}
package Practice_test;
public class Test_maxiao {
public static void main(String[] args) {
System.out.println(removeFourChar("えもじ,e-moji,moj"));
}
/**
* 替换四个字节的字符 '\xF0\x9F\x98\x84\xF0\x9F)的解决方案
*
* @param content
* @return
* @author 张栋
* @data 2015年8月11日 上午10:31:50
*/
public static String removeFourChar(String content) {
byte[] conbyte = content.getBytes();
System.out.println(conbyte[0]);
for (int i = 0; i < conbyte.length; i++) {
if ((conbyte[i] & 0xF8) == 0xF0) {
for (int j = 0; j < 4; j++) {
System.out.println("j="+j);
conbyte[i + j] = 0x30;
}
i += 3;
}
}
String contentnew = new String(conbyte);
return contentnew.replaceAll("0000", "");
}
}
package Practice_test;
//package test;
//
//
//
//import com.puhui.bestbuy.common.domain.wx.Token;
//import com.puhui.bestbuy.common.domain.wx.WeixinOauth2Token;
//import com.puhui.bestbuy.common.domain.wx.WeixinUserInfo;
//import com.puhui.bestbuy.common.domain.wx.WeixinUserList;
//import net.sf.json.JSONArray;
//import net.sf.json.JSONException;
//import net.sf.json.JSONObject;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import java.security.MessageDigest;
//import java.security.NoSuchAlgorithmException;
//import java.util.Arrays;
//import java.util.List;
//
//
///**
// * @ClassName: UserUtil.java
// * @Title: 权限控制工具类
// * @Description: 权限控制工具类
// */
//public class UserUtil {
//
// private static final String errcode = "errcode";
//
// private static final String errmsg = "errmsg";
//
// private static Logger log = LoggerFactory.getLogger(UserUtil.class);
//
// public static Token getToken(String appid, String appsecret) {
// Token token = null;
// String requestUrl = WeixinParameter.token_url.replace("APPID", appid)
// .replace("APPSECRET", appsecret);
// // 发起GET请求获取凭证
// JSONObject jsonObject = CommonUtil
// .httpsRequest(requestUrl, "GET", null);
//
// if (null != jsonObject) {
// try {
// token = new Token();
// token.setAccessToken(jsonObject.getString("access_token"));
// token.setExpiresIn(jsonObject.getInt("expires_in"));
// log.info("[UserUtil][getToken]获取token成功{}", jsonObject.getString("access_token"));
// } catch (JSONException e) {
// token = null;
// // 获取token失败
// log.error("[UserUtil][getToken]获取token失败 errcode:{} errmsg:{}",
// jsonObject.getInt(errcode),
// jsonObject.getString(errmsg));
// log.error("获取token失败", e);
// }
// }
// return token;
// }
//
// /**
// * 获取用户信息
// *
// * @param accessToken 接口访问凭证
// * @param openId 用户标识
// * @return WeixinUserInfo
// */
// public static WeixinUserInfo getUserInfo(String accessToken, String openId) {
// WeixinUserInfo weixinUserInfo = new WeixinUserInfo();
// // 拼接请求地址
// String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID";
// requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace(
// "OPENID", openId);
// // 获取用户信息
// JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
//
// if (null != jsonObject) {
// log.info("[UserUtil][getUserInfo][jsonObject]="
// + jsonObject.toString());
// // 用户的标识
// weixinUserInfo.setOpenId(openId);
// // 关注状态(1是关注,0是未关注),未关注时获取不到其余信息
// weixinUserInfo.setSubscribe(jsonObject.getInt("subscribe"));
// if (jsonObject.getInt("subscribe") == 1) {
// // 用户关注时间
// weixinUserInfo.setSubscribeTime(jsonObject
// .getString("subscribe_time"));
// // 昵称
// weixinUserInfo.setNickname(jsonObject.getString("nickname"));
// // 用户的性别(1是男性,2是女性,0是未知)
// weixinUserInfo.setSex(jsonObject.getInt("sex"));
// // 用户所在国家
// weixinUserInfo.setCountry(jsonObject.getString("country"));
// // 用户所在省份
// weixinUserInfo.setProvince(jsonObject.getString("province"));
// // 用户所在城市
// weixinUserInfo.setCity(jsonObject.getString("city"));
// // 用户的语言,简体中文为zh_CN
// weixinUserInfo.setLanguage(jsonObject.getString("language"));
// // 用户头像
// weixinUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
// }
// }
// return weixinUserInfo;
// }
//
// /**
// * 校验签名
// *
// * @param token 绑定TOKEN
// * @param signature 微信加密签名
// * @param timestamp 时间戳
// * @param nonce 随机数
// * @return
// */
// public static boolean checkSignature(String token, String signature,
// String timestamp, String nonce) {
//
// // 对token、timestamp和nonce按字典排序
// String[] paramArr = new String[]{token, timestamp, nonce};
// Arrays.sort(paramArr);
//
// // 将排序后的结果拼接成一个字符串
// String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);
//
// String ciphertext = null;
// try {
// MessageDigest md = MessageDigest.getInstance("SHA-1");
// // 对接后的字符串进行sha1加密
// byte[] digest = md.digest(content.getBytes());
// ciphertext = CommonUtil.byteToStr(digest);
// } catch (NoSuchAlgorithmException e) {
// log.error("验签失败", e);
// }
//
// // 将sha1加密后的字符串与signature进行对比
// log.info("ciphertext:" + ciphertext);
// return ciphertext != null ? ciphertext.equalsIgnoreCase(signature)
// : false;
// }
//
// /**
// * 获取网页授权凭证
// *
// * @param appId 公众账号的唯一标识
// * @param appSecret 公众账号的密钥
// * @param code
// * @return WeixinAouth2Token
// */
// public static WeixinOauth2Token getOauth2AccessToken(String appId,
// String appSecret, String code) {
// WeixinOauth2Token wat = null;
// // 拼接请求地址
// String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
// requestUrl = requestUrl.replace("APPID", appId);
// requestUrl = requestUrl.replace("SECRET", appSecret);
// requestUrl = requestUrl.replace("CODE", code);
// // 获取网页授权凭证
// JSONObject jsonObject = CommonUtil
// .httpsRequest(requestUrl, "GET", null);
// if (null != jsonObject) {
// try {
// wat = new WeixinOauth2Token();
// wat.setAccessToken(jsonObject.getString("access_token"));
// wat.setExpiresIn(jsonObject.getInt("expires_in"));
// wat.setRefreshToken(jsonObject.getString("refresh_token"));
// wat.setOpenId(jsonObject.getString("openid"));
// wat.setScope(jsonObject.getString("scope"));
// } catch (Exception e) {
// wat = null;
// int errorCode = jsonObject.getInt(errcode);
// String errorMsg = jsonObject.getString(errmsg);
// log.error(
// "[UserUtil][getOauth2AccessToken]获取网页授权凭证失败 errcode:{} errmsg:{}",
// errorCode, errorMsg);
// log.error("获取网页授权凭证失败", e);
// }
// }
// return wat;
// }
//
// /**
// * 获取关注者列表
// *
// * @param accessToken 调用接口凭证
// * @param nextOpenId 第一个拉取的openId,不填默认从头开始拉取
// * @return WeixinUserList
// */
// @SuppressWarnings({"unchecked", "deprecation"})
// public static WeixinUserList getUserList(String accessToken,
// String nextOpenId) {
// WeixinUserList weixinUserList = new WeixinUserList();
//
// if (null == nextOpenId)
// nextOpenId = "";
//
// // 拼接请求地址
// String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID";
// requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace(
// "NEXT_OPENID", nextOpenId);
// // 获取关注者列表
// JSONObject jsonObject = CommonUtil
// .httpsRequest(requestUrl, "GET", null);
// // 如果请求成功
// if (null != jsonObject) {
// weixinUserList.setTotal(jsonObject.getInt("total"));
// weixinUserList.setCount(jsonObject.getInt("count"));
// weixinUserList.setNextOpenId(jsonObject
// .getString("next_openid"));
// JSONObject dataObject = (JSONObject) jsonObject.get("data");
// weixinUserList.setOpenIdList(JSONArray.toList(
// dataObject.getJSONArray("openid"), List.class));
//
// }
// return weixinUserList;
// }
//
//}
package Practice_test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Decoder;
/**
* 验证码识别类
* 第一个参数:几位的中英数
* 第二个参数:图片地址
* 返回解析好的字符串
* @author puhui
*/
public class aliOCR {
public static void main(String[] args) {
// String YanZhengMa=getYZM(4,"d:\\t111.jpg");
//// getYZM(4,"d:\\abc.jpg");
// System.out.println("验证码="+YanZhengMa);
//将字符串转换成图片
boolean b=GenerateImage("/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAA0AIADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD3+ikZlRSzEBQMkk8AVB9sjb/VLJMe3lrlT9G+7+tK6FcsU2RC8TosjRsykB1xlT6jIIz9QahzdycgRQjsGBcn64Ix+Zo+xo3+ueSf2kPy/iowD+Iov2AoC9vLG4W3nC36FgvmQACZAe8kfQgDkspHJACVYtNS/tGIvZqu1W2OZHGUb0KjJDDPKnaRV1I0iQJGioo6KowBWZcaIl9cy3F3Nl2QxIYYwhVM5AYnJfqcqTsPdKrffQm0lsy9b3UNw0kccySvCdspjHyhu4z0zxyM5GRnqKnrKja+0qNYpIFu7OMBVktkCyRqOm6Po2AOSnJJACVetL22vojJbTLIqttYDqjd1YdVYZ5BwR3puLWo1JPQnoooqSgopjyrGyBgQGOA3YHsD9f89RT6AuFFFFABRRRQA140k270Vtp3DIzg+tOoooAKKKKACiiigDAfxKYfGSeH57FkE0XmQXAlBDjaScrjgfK469hxg5rak8iDzbqTy48J+8lbAwi5PJ9Bkn2ya5T4h2E8uj2+q2S/6ZpkwnVwCSqdyBgg4IVjnoFP4y2E3/Cb7byWKSLQ4n/d20q4a6kGDufsUU8BQSCQc9MV0unFwU1otn6/8E5lUkpuD1e69P8AgGvomrvq+mNqE1m9lAzMYfOYZeLs5/u5549s5IINT6bqSalFI6Ls2Pt2lsnHYn0/+tUV9/p9yunL/q12yXDdtueE9ievbgd6q6but/EWoW+QyuPNJxznIOP/AB41yTneeish88lKKvdbfMvw3i3l5c2ohDRRDazk8E9MYx9fyqTe1r8sm54B0lJyUH+13x7/AJ9MmhoP737Zd9POl+76d+v/AAL9Km8QagdL0C9vFLCRI8IVAOHPyqcHjgkUoXkrmq1VypqPiaG2uxY6fbyalfnrDARtj+YKd7fw/wBO+M5qGTxFqdlG0+p+HbmG3UEl7eZJyO/IGMDAPP8AjSeDdNbTtEt5SqPJeqJpZAfmyeVyT1GCOOxz1zkdJVjV2FFFFBQUUUUAFFFFABRRRQBzPxAufs3gu/xN5TybI1w+0tlxlR65Xdkemat6S8ejeENP82IQNHax5iK7CZCoJBGOpbOfxJq7qujWGt2q22owedCriQLvZcMARnKkdiatS28UzxvIu4xtuTJOAfXHTP8AKtJT/dKC3vcxdOXtHNdrIyrbTNRQNL/aPlyzYaQGBWOcdM56D8qz9VS50+9t7ma6NxK6OikIEK8Yzx/vZrqax7q2vtUt0hnt47fY4YuZN2eCDgD69zXLOFlZEzorltG9/mWNEj8vSYcptLZY8YzycH8sVS8ZQSXHhLUEiXcwRXIyB8qsGJ/IGtuNFijWNBhVAUD0Ap1axVkkbpaWMLwlqlrqPh+1S3kzJbRJDKh4ZWC46ehxwf6gisvUf9L+JumQ/wCuitrcu6feWJsOQSP4T9zn/d9q2L3wpoeoXJuLjT4zK33mRmTcck5O0jJ569as6boWmaRuNjZxxM2cvyzY443HJxwOOlUKzNCiiikUFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQB//9k=");
System.out.println(b);
}
public static String getYZM(int count,String imagePath){
String host = "http://ali-checkcode.showapi.com";
String path = "/checkcode";
String method = "POST";
Map<String, String> headers = new HashMap<String, String>();
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE 4afc3a5a191a4bbd80b837c3374ac872");
Map<String, String> querys = new HashMap<String, String>();
Map<String, String> bodys = new HashMap<String, String>();
bodys.put("convert_to_jpg", "0");
bodys.put("img_base64", encodeImgageToBase64(new File(imagePath)));
bodys.put("typeId", "30"+count+"0");
String result=null;
try {
HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
result=EntityUtils.toString(response.getEntity());
JSONObject obj = JSONObject.fromObject(result);
result=obj.getString("showapi_res_body");
JSONObject obj1 = JSONObject.fromObject(result);
result=obj1.get("Result").toString();
System.out.println("获取的验证码是:"+obj1.get("Result"));
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static String encodeImgageToBase64(File imageFile) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
// 其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(imageFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return new String(Base64.encodeBase64(data));
}
//base64字符串转化成图片
public static boolean GenerateImage(String imgStr)
{ //对字节数组字符串进行Base64解码并生成图片
if (imgStr == null) //图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try
{
//Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for(int i=0;i<b.length;++i)
{
if(b[i]<0)
{//调整异常数据
b[i]+=256;
}
}
//生成jpeg图片
String imgFilePath = "d://222.jpg";//新生成的图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
}
catch (Exception e)
{
return false;
}
}
}
package Practice_test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import com.offcn.TestUnti.MapUtil;
public class map_show {
public static void main(String[] args) throws Exception {
Map<String,String> map=new HashMap<String,String>();
map.put("a","1");
map.put("b","2");
map.put("c","3");
System.out.println(showMap(map,"d"));
// String ss=show();//把map中parameter对应的内容拿出来
// String sss=getPhone(ss,"phone");//在parameter中查看,是否有关键字
// System.out.println("sss="+sss+"==");
// if(sss==null){
// System.out.println("等于空");
// }
// if(sss.equals("")){
// System.out.println("等于空字符串");
// }
}
//查找map中是否有这个建
public static boolean showMap(Map<String, String> data,String key){
Set<Map.Entry<String,String>> set=data.entrySet();
Iterator<Entry<String, String>> it=set.iterator();
while(it.hasNext()){
Map.Entry<String,String> me=it.next();
if(me.getKey().equals(key)){
return true;
}
}
return false;
}
public static String getPhone(String parameter,String phone){
String[] strcomma=parameter.split(",");
int comma=strcomma.length;
StringBuffer sb=new StringBuffer();
for(int k=0;k<comma;k++){
//此时是多个,,,
String[] str=strcomma[k].split(":");
String str_strcomma=Arrays.toString(str);
System.out.println("str="+Arrays.toString(str));
//按参数传过来的字符串做为子串,在以逗号为节点的串中分别查找子串的关键字,
//在找到后的位置开始查找数字,最后把数字的字符串返回
if(str_strcomma.contains(phone)){
for (int i =0;i< str_strcomma.length(); i++) {
if (Character.isDigit(str_strcomma.charAt(i))) {
sb.append(str_strcomma.charAt(i));
}
}
}
}
return sb.toString();
}
//查看二维数组
public static String show() throws Exception{
//查看二维数组
ReadExcels readExcels = new ReadExcels("DataAll.xls","TestCase");
Object[][] arrmap= readExcels.readExcels_return();
for(int i=0;i<arrmap.length;i++){
for(int j=0;j<arrmap[i].length;j++){
System.out.print(","+arrmap[i][j]);
}
System.out.println();
}
// HashMap<String, Object> hm=new HashMap<String, Object>();
// hm=(HashMap<String, Object>) arrmap[0][0];
String s=MapUtil.getValue("parameter",(HashMap<String, Object>) arrmap[38][0]);
System.out.println("s="+s);
return s;
}
}
package Practice_test;
import static io.restassured.http.ContentType.JSON;
import java.util.List;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.response.Response;
public class maxiao implements Runnable{
public String JSESSIONID;
public String StatusCode;
public String time;
public maxiao(String jSESSIONID) {
JSESSIONID = jSESSIONID;
}
@Override
public void run() {
// RestAssured ra_VerifyCode = new RestAssured();
// ra_VerifyCode.baseURI = "http://10.10.197.245";
// ra_VerifyCode.port = 8888;
// ra_VerifyCode.basePath = "/puhui-lend-pre/page/lendRepay/repayList.jsp";
//
// Long start=System.currentTimeMillis();
// Response re2 = ra_VerifyCode.given().given().
// headers("Cookie", JSESSIONID,
// "Referer","http://10.10.197.245:8888/puhui-lend-pre/main",
// "Upgrade-Insecure-Requests","1"
// ).get();
// Long end=System.currentTimeMillis();
//
// time=(end-start)+"";
// System.out.println();
// StatusCode=re2.getStatusCode()+"";
// System.out.println(re2.getBody().asString());
// System.out.print("名称:"+Thread.currentThread().getName()+"状态:"+re2.getStatusCode()+"耗时:"+time+"毫秒");
RestAssured ra_VerifyCode = new RestAssured();
ra_VerifyCode.baseURI = "http://10.10.197.245";
ra_VerifyCode.port = 8888;
ra_VerifyCode.basePath = "/puhui-lend-pre/lendRepay/list ";
String Parameter="{\"billDate\":\"2016-12-25\",\"page\":1,\"rows\":20}";
System.out.println(Parameter);
Long start=System.currentTimeMillis();
Response re2 = ra_VerifyCode.given().given().contentType(JSON).
headers("Cookie", "JSESSIONID=17E32712D50602F82C30A29E827343E6",
"Referer"," http://10.10.197.245:8888/puhui-lend-pre/page/lendRepay/repayList.jsp",
"Origin","http://10.10.197.245:8888"
).body(Parameter).when().post();
Long end=System.currentTimeMillis();
time=(end-start)+"";
System.out.println(re2.getBody().asString());
System.out.print("名称:"+Thread.currentThread().getName()+"状态:"+re2.getStatusCode()+"耗时:"+time+"毫秒");
}
public static void main(String[] args) {
RestAssured ra_VerifyCode = new RestAssured();
ra_VerifyCode.baseURI = "http://10.10.197.245";
ra_VerifyCode.port = 8888;
ra_VerifyCode.basePath = "/puhui-lend-pre/lendRepay/list";
String Parameter="{\"billDate\":\"2016-12-25\",\"page\":1,\"rows\":20}";
System.out.println(Parameter);
Long start=System.currentTimeMillis();
Response re2 = ra_VerifyCode.given().given().contentType(ContentType.URLENC).
headers("Cookie", "JSESSIONID=17E32712D50602F82C30A29E827343E6",
"Referer"," http://10.10.197.245:8888/puhui-lend-pre/page/lendRepay/repayList.jsp",
"Origin","http://10.10.197.245:8888"
).body("billDate=2016-12-25&page=1&rows=20").when().post();
Long end=System.currentTimeMillis();
System.out.println(re2.getBody().asString());
System.out.print("名称:"+Thread.currentThread().getName()+"状态:"+re2.getStatusCode()+"耗时:毫秒");
}
}
package Practice_test;
import java.util.Arrays;
public class panduanshifushishuzi {
public static void main(String[] args) {
String p="\"phone\":\"13910960649\",\"thirdSource\":\"GM\",\"thirdSourceId\":\"ys\",\"verifyCode\":codeown";
System.out.println(getChar(p,"verifyCode"));
}
//判断数字
public static void shuzipanduan(){
String str="12345uu7";
for (int i =0;i< str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
System.out.println(str.charAt(i));
}
}
}
//判断字母
public static String getChar(String parameter,String Letter){
String[] strcomma=parameter.split(",");
int comma=strcomma.length;
StringBuffer sb=new StringBuffer();
for(int k=0;k<comma;k++){
//此时是多个,,,
String[] str=strcomma[k].split(":");
String str_strcomma=Arrays.toString(str);
System.out.println("str="+Arrays.toString(str));
//按参数传过来的字符串做为子串,在以逗号为节点的串中分别查找子串的关键字,
//在找到后的位置开始查找数字,最后把数字的字符串返回
if(str_strcomma.contains(Letter)){
int start=str_strcomma.indexOf(',');
sb.append(str_strcomma.substring(start+1,str_strcomma.length()-1));
}
}
return sb.toString();
}
}
package Practice_test;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class properties_test {
public static void main(String[] args) throws Exception{
test3();
// ClearProperty();
}
public static void ClearProperty() {
File directory = new File(".");
try {
String sourceFile = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator+"information.properties";
File file =new File(sourceFile);
if(!file.exists()) {
file.createNewFile();
}
FileWriter fileWriter =new FileWriter(file);
fileWriter.write("");
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void test3() throws Exception{
Properties prop = new Properties();// 属性集合对象
FileInputStream fis = new FileInputStream("src/resources/information.properties");// 属性文件输入流
prop.load(fis);// 将属性文件流装载到Properties对象中
System.out.println(prop.isEmpty());
fis.close();// 关闭流
}
public static void test2() throws Exception {
Properties prop = new Properties();// 属性集合对象
FileInputStream fis = new FileInputStream("src/resources/information.properties");// 属性文件输入流
prop.load(fis);// 将属性文件流装载到Properties对象中
fis.close();// 关闭流
// 获取属性值,sitename已在文件中定义
System.out.println("获取属性值:password=" + prop.getProperty("password"));
// 获取属性值,country未在文件中定义,将在此程序中返回一个默认值,但并不修改属性文件
// System.out.println("获取属性值:country=" + prop.getProperty("country", "中国"));
// 修改sitename的属性值
prop.setProperty("password", "heihei");
// 文件输出流
FileOutputStream fos = new FileOutputStream("src/resources/information.properties");
// 将Properties集合保存到流中
prop.store(fos, "Copyright (c) Boxcode Studio");
fos.close();// 关闭流
System.out.println("获取修改后的属性值:password=" + prop.getProperty("password"));
}
public static String test1(){
Properties prop = new Properties();
try {
File directory = new File(".");
String sourceFile = directory.getCanonicalPath() +File.separator+"src"+File.separator+"resources"+File.separator+"xyzb.properties";
FileOutputStream oFile = new FileOutputStream(sourceFile, true);//true表示追加打开
prop.setProperty("phone", "10086");
prop.store(oFile, "The New properties file");
oFile.close();
return "";
}catch (IOException e) {
return null;
}
}
}
package Practice_test;
import java.util.Iterator;
import java.util.Set;
import com.beust.jcommander.Parameter;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class t1 {
public static String killQuotes(String parameter, String letter){
StringBuffer sb=new StringBuffer();
for(int k=0;k<parameter.length();k++){
if(parameter.charAt(k)!= '"'){
sb.append(parameter.charAt(k));
}
}
return sb.toString();
}
public static void main(String[] args) {
String parameter = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo4NTgxOCwiYXJlYV9jb2RlIjoiODYiLCJwaG9uZSI6IjE4MzM5OTcwOTI1IiwiY3JlYXRlX3RpbWUiOjE1NDMxOTYyMjIsInVwZGF0ZV90aW1lIjoxNTQ1MDI1Mjk0LCJzeXN0ZW0iOiJCTEEtQUwwMEhVQVdFSSIsInBsYXRmb3JtIjoiQW5kcm9pZCIsImlwIjoiNjEuMTQ5LjIwLjExNCIsInZlcnNpb24iOiIxIiwiZGV2aWNlX2lkIjoiODY2MjE3MDM3MjkxNzk5IiwicGFzc3dkIjoiM2I1MDY1ZGRiYzhiMWRjMDM2ZmZkMzg4NDYzZTRlYmIiLCJuaWNrbmFtZSI6Ilx1OTUyNi4iLCJhdmF0YXIiOiJodHRwOlwvXC90aGlyZHFxLnFsb2dvLmNuXC9xcWFwcFwvMTEwNjc3MzY4MVwvNjFDQkEwNzhBMTdCMjVERjk4MENEMDFBMjNGQjdBNDZcLzEwMCIsImdlbmRlciI6ImYiLCJxcV9pZCI6IjYxQ0JBMDc4QTE3QjI1REY5ODBDRDAxQTIzRkI3QTQ2Iiwid2VpYm9faWQiOiIiLCJ3ZWl4aW5faWQiOiIiLCJ1bmlvbl9pZCI6IiIsIndlaWJvX25pY2tuYW1lIjoiIiwicXFfbmlja25hbWUiOiJcdTk1MjYuIiwid2VpeGluX25pY2tuYW1lIjoiIiwid2VpYm9fYXZhdGFyIjoiIiwicXFfYXZhdGFyIjoiaHR0cDpcL1wvdGhpcmRxcS5xbG9nby5jblwvcXFhcHBcLzExMDY3NzM2ODFcLzYxQ0JBMDc4QTE3QjI1REY5ODBDRDAxQTIzRkI3QTQ2XC8xMDAiLCJ3ZWl4aW5fYXZhdGFyIjoiIiwibG9naW5fdHlwZSI6InFxIiwicGhvbmVfbmFtZSI6IiIsInBob25lX2F2YXRhciI6IiIsInN0b3JlIjoib2ZmY24iLCJpZl9kZWxldGUiOjAsImV4YW1faWQiOjcxLCJpdGVtX2lkIjoxMTIsImV4YW1fYXJlYSI6Ilx1NTZmZFx1NWJiNlx1NTE2Y1x1NTJhMVx1NTQ1OFx1ODAwM1x1OGJkNSIsImlhdCI6MTU0NTAyNTMwMCwibmJmIjoxNTQ1MDI1MzAwLCJleHAiOjE1NzY1NjEzMDB9.Y-6ZSY2Tqr8xdIvKR4ThenzYt17-0vFMBN3RBFATmj8";
String sb = killQuotes(parameter, "\"");
System.out.println(sb);
/*
String str="{\"houseBasicInfo\": {\"address\": \"***&*&*&87\",\"area\": \"北京市\",\"cardPic\": \"cardpiccardpiccardpic\",\"city\": \"北京市\",\"contract\": \"contract\",\"contractNo\": \"100000004\",\"idNo\": \"11022119811222061X\",\"name\": \"姚帅\",\"payAmount\": 10000,\"phone\": \"13910960649\",\"rentBegin\": \"2017-07-21\",\"rentEnd\": \"2018-07-21\",\"rental\": 5000,\"rentalType\": 1,\"roomId\": \"11\",\"roomNum\": \"1101室\",\"suiteId\": \"111\",\"termNum\": 12,\"thirdUserId\": \"1\",\"timeStamp\": \"123123123\"},\"merchantName\": \"蛋壳第一商户\",\"receiveContractInfo\": {\"area\": \"北京\",\"attachment\": \"attachment\",\"city\": \"北京\",\"contractNo\": \"0000001231231231\",\"endTime\": \"2017-07-21\",\"personIdNo\": \"110102198907132328\",\"personName\": \"小五\",\"rentalAddress\": \"北京市朝阳区银河SOHO1101室\",\"startTime\": \"2018-07-21\",\"subCompany\": \"蛋壳租房\"},\"source\": 0}";
JSONObject jo = JSONObject.fromObject(str);
System.out.println(jo.getString("houseBasicInfo"));
JSONObject j1 = JSONObject.fromObject(jo.getString("houseBasicInfo"));
System.out.println(j1.getString("address"));
System.out.println(j1.getString("area"));
System.out.println(j1.getString("cardPic"));
System.out.println("====================================");
System.out.println(jo.getString("merchantName"));
System.out.println(jo.getString("receiveContractInfo"));
System.out.println(jo.getString("source"));*/
// Iterator it=jo.keys();
// String key=null;
// String value=null;
// while(it.hasNext()){
// key=(String)it.next();
// value=jo.getString(key);
// System.out.println(value);
// }
// JSONObject obj = JSONObject.fromObject(str);
// String showapi=obj.getString("showapi_res_body");
// JSONObject obj1 = JSONObject.fromObject(showapi);
// System.out.println(obj1.get("Result"));
// JSONArray transitListArray = obj.getJSONArray("showapi_res_body");
// System.out.println(transitListArray.getString("Result"));
// for (int i = 0; i < transitListArray.size(); i++) {
// System.out.print("Array:" + transitListArray.getString(i) + " ");
// }
// System.out.println(jo.getString("Result"));
// System.out.println(jo.get("list"));
// JSONObject jo1 = (JSONObject)jo.get("list");
// System.out.println(jo1.get("phone"));
}
}
package Practice_test;
import java.util.Arrays;
public class test {
public static void main (String[] args) {
String res1 = "page=1&size=10&username=code&phone=code&card_no=code&status=1";
String sss=getParameter_get(res1,"size");
System.out.println(sss);
}
//在parameter中获取get请求中的参数
public static String getParameter_get(String parameter,String Letter){
if(parameter==null){
return "";
}
String[] strcomma=parameter.split("&");
int comma=strcomma.length;
StringBuffer sb=new StringBuffer();
for(int k=0;k<comma;k++){
String str_strcomma=strcomma[k];
if(str_strcomma.contains(Letter)){
int start=str_strcomma.indexOf('=');
sb.append(str_strcomma.substring(start+1,str_strcomma.length()));
return sb.toString();
}
}
return sb.toString();
}
}
package Practice_test;
import java.text.SimpleDateFormat;
import java.util.Random;
import sun.net.www.http.HttpClient;
public class test1 {
public static void main(String[] args) {
String a1=null;
String a2="";
if("0".equals(a1)){
System.out.println(1);
}else{
System.out.println(2);
}
}
}
//SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
//String dateStr = dateformat.format(System.currentTimeMillis());
//System.out.println(dateStr);
//System.out.println(new Random().nextInt(90000000)+ 10000000);
package Practice_test;
import java.lang.reflect.Method;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class testng1 {
@DataProvider(name = "user")
public Object[][] createUser(Method m) {
System.out.println(m.getName());
return new Object[][] { { "root", "root" }, { "test", "root" }, };
}
@Test(groups = "login", dependsOnGroups = "launch", dataProvider = "user")
public void verifyUser(String username, String password) {
System.out.println("Verify User : " + username + ":" + password);
assert username.equals(password);
}
}
package Practice_test;
import com.offcn.TestUnti.MyDateUtil;
public class time_test {
public static void main(String[] args) {
System.out.println("rile1111222");
System.out.println(MyDateUtil.getTime(0, -10, 0));
}
}
package Practice_test;
import net.sf.json.JSONObject;
import com.offcn.TestUnti.SheetUtils;
import com.offcn.TestUnti.StringUtils;
public class w_excel {
public static void main(String[] args) {
SheetUtils sheet = new SheetUtils("a1.xls", "Output");
sheet.writeExcel(
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10"
);
}
}
package com.offcn.api.nwn;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import org.json.simple.JSONArray;
import com.offcn.TestUnti.Log;
import com.offcn.TestUnti.MapUtil;
import com.offcn.TestUnti.RequestDataUtils;
import com.offcn.TestUnti.StringUtils;
import com.offcn.interfaces.API;
import com.offcn.process.NWN;
import com.offcn.process.TK;
import com.offcn.TestUnti.ListUtil;
import net.sf.json.JSONObject;
/**
* 学习包信息-常态
*
* @author liyy
*
*/
public class isValidLevel extends NWN implements API {
public String parameter;//参数集合
public String package_id;//搜索-学习包id
public String id;//层级包id
@Override
public void initialize(HashMap<String, Object> data) {
}
@Override
public HashMap<String, Object> handleInput(HashMap<String, Object> data) {
// 获取parameter对应的内容
parameter = MapUtil.getValue("parameter", data);
package_id = MapUtil.getParameter_get(parameter, "package_id").trim();
id = MapUtil.getParameter_get(parameter, "id").trim();
if ((!package_id.equals("")) && package_id.equals("package_id")) {
package_id=ListUtil.getListValue(n_package_idList, 0);
parameter = parameter.replace("package_id=package_id", "package_id="+ package_id );
}
if ((!id.equals("")) && id.equals("formation_id")) {
id=level_id_List;
System.out.println("id======"+id);
parameter = parameter.replace("id=formation_id", "id="+ id );
}
data.put("parameter", parameter);
return data;
}
@Override
public Response SendRequest(HashMap<String, Object> data, String Url,
String Request) {
Response re = RequestDataUtils.Get_one_cookie_pre(data, Url, "PHPSESSID",PHPSESSID);
//Response re = RequestDataUtils.Get_one_cookie(data, serviceURL, cookie1Name, cookie1value) //只能无参
// Response re = RequestDataUtils.Get_token(data, Url, "");
return re;
}
@Override
public String handleOutput(Response re, HashMap<String, Object> data) {
JsonPath jp = re.body().jsonPath();
boolean result = true;
String failReason = "";
String json = re.asString();
if ((data.get("statusCode") != null)
&& (!data.get("statusCode").toString()
.equals(String.valueOf(re.getStatusCode())))) {
result = result && false;
failReason = failReason + "statusCode is expected "
+ data.get("statusCode").toString() + " but actually "
+ String.valueOf(re.getStatusCode()) + ". ";
}
if (json.length() != 0) {
String msg=StringUtils.decodeUnicode(getMsg(re));
String code=getCode(re);
if ((data.get("code") != null ) && (code != null) && (!code.equals(data.get("code").toString()))) {
result = result && false;
failReason = failReason + "code is expected "
+ data.get("code").toString() + " but actually "
+ jp.getString("code") + ".";
}
if ((data.get("msg") != null) && (msg != null) && (!msg.equals(data.get("msg").toString()))) {
result = result && false;
failReason = failReason + "msg is expected "
+ data.get("msg").toString() + " but actually "
+ jp.getString("msg") + ".";
}
if(data.get("custom") != null && jp.getString("data")!=null){
String custom=data.get("custom").toString();
String[] ArrayString=StringUtils.getArrayString(custom,",");
if(!StringUtils.VerificationString(jp.getString("data"),ArrayString)){
result = result && false;
failReason = failReason + "custom is expected "
+ data.get("custom").toString() + " but actually "
+ jp.getString("data") + ".";
}
}
if("添加成功!".equals(msg)){
//是否验证数据库
if (!isProduct) {
}
}
}
if (result)
return "Pass";
else
return "Fail:" + failReason;
}
}
package com.offcn.api.nwn;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import org.json.simple.JSONArray;
import com.offcn.TestUnti.Log;
import com.offcn.TestUnti.MapUtil;
import com.offcn.TestUnti.RequestDataUtils;
import com.offcn.TestUnti.StringUtils;
import com.offcn.interfaces.API;
import com.offcn.process.NWN;
import com.offcn.process.TK;
import com.offcn.TestUnti.ListUtil;
import net.sf.json.JSONObject;
/**
* 学习包信息-常态
*
* @author liyy
*
*/
public class viewUnitPackage extends NWN implements API {
public String parameter;//参数集合
public String package_id;//搜索-学习包id
@Override
public void initialize(HashMap<String, Object> data) {
}
@Override
public HashMap<String, Object> handleInput(HashMap<String, Object> data) {
// 获取parameter对应的内容
parameter = MapUtil.getValue("parameter", data);
package_id = MapUtil.getParameter_get(parameter, "package_id").trim();
if ((!package_id.equals("")) && package_id.equals("id")) {
package_id=ListUtil.getListValue(n_package_idList, 0);
parameter = parameter.replace("package_id=id", "package_id="+ package_id );
}
data.put("parameter", parameter);
return data;
}
@Override
public Response SendRequest(HashMap<String, Object> data, String Url,
String Request) {
Response re = RequestDataUtils.Get_one_cookie_pre(data, Url, "PHPSESSID",PHPSESSID);
//Response re = RequestDataUtils.Get_one_cookie(data, serviceURL, cookie1Name, cookie1value) //只能无参
// Response re = RequestDataUtils.Get_token(data, Url, "");
return re;
}
@Override
public String handleOutput(Response re, HashMap<String, Object> data) {
JsonPath jp = re.body().jsonPath();
boolean result = true;
String failReason = "";
String json = re.asString();
if ((data.get("statusCode") != null)
&& (!data.get("statusCode").toString()
.equals(String.valueOf(re.getStatusCode())))) {
result = result && false;
failReason = failReason + "statusCode is expected "
+ data.get("statusCode").toString() + " but actually "
+ String.valueOf(re.getStatusCode()) + ". ";
}
if (json.length() != 0) {
String msg=StringUtils.decodeUnicode(getMsg(re));
String code=getCode(re);
if ((data.get("code") != null ) && (code != null) && (!code.equals(data.get("code").toString()))) {
result = result && false;
failReason = failReason + "code is expected "
+ data.get("code").toString() + " but actually "
+ jp.getString("code") + ".";
}
if ((data.get("msg") != null) && (msg != null) && (!msg.equals(data.get("msg").toString()))) {
result = result && false;
failReason = failReason + "msg is expected "
+ data.get("msg").toString() + " but actually "
+ jp.getString("msg") + ".";
}
if(data.get("custom") != null && jp.getString("data")!=null){
String custom=data.get("custom").toString();
String[] ArrayString=StringUtils.getArrayString(custom,",");
if(!StringUtils.VerificationString(jp.getString("data"),ArrayString)){
result = result && false;
failReason = failReason + "custom is expected "
+ data.get("custom").toString() + " but actually "
+ jp.getString("data") + ".";
}
}
if("添加成功!".equals(msg)){
//是否验证数据库
if (!isProduct) {
}
}
}
if (result)
return "Pass";
else
return "Fail:" + failReason;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment