开发经验总结

总结一

1、提取HTML标签的属性值

    /**
     * 提取HTML标签的属性值
     * @param source HTML标签内容
     * @param element 标签名称  img
     * @param attr 标签属性   src
     * @return
     */
    public List<String> match(String source, String element, String attr) {
         List<String> result = new ArrayList<String>();
         String reg = "<" + element + "[^<>]*?\\s" + attr + "=['\"]?(.*?)['\"]?\\s.*?>";
         Pattern pt = Pattern.compile(reg);
         Matcher m = pt.matcher(source);
         while (m.find()) {
                 String r = m.group(1);
                 result.add(r);
             }
         return result;
    }

2、JPA下执行原生SQL

/**
     * 返回sql查询的所有集合 元素为map key值为columns
     *
     * @param sql
     *            具体执行sql 查询sql包含多列
     * @param columns
     *            columns nativesql查询出为对象数组,将其转换为map,columns为列名数组,顺序和sql语句中列一致 例如{"列名1","列名2"}
     * @return
     */
    protected List<Map<String, Object>> handleNativeSql(String sql, String[] columns) {
        List<Map<String, Object>> list = handleSql(sql, null, columns);
        return list;
    }
    private List<Map<String, Object>> handleSql(String sql, PageRequest pageRequest, String[] columns) {
        Query query = entityManager.createNativeQuery(sql);

        if (pageRequest != null) {
            query.setFirstResult(pageRequest.getPageNumber() * pageRequest.getPageSize());
            query.setMaxResults(pageRequest.getPageSize());
        }

        List<Object[]> list = query.getResultList();

        List<Map<String, Object>> list_ = new ArrayList<>();
        Map<String, Object> map = null;

        String key = "0";
        for (Object[] arrs : list) {
            map = new HashMap<String, Object>();
            for (int i = 0; i < arrs.length; i++) {
                key = columns == null ? i + "" : columns[i];
                map.put(key, arrs[i]);
            }
            list_.add(map);
        }

        return list_;
    }

3、文件拷贝

/**
     * 利用NIO 拷贝 推荐使用
     * @param sourcePath 源文件路径 /data/website/abc.txt
     * @param targetPath 目标路径 /data/website2/
     * @param fileName 目标文件 abcd.txt
     */
    public static void copyNioTransfer(String sourcePath, String targetPath, String fileName) {
        File source = new File(sourcePath);
        File targetDir = new File(targetPath);
        if (!targetDir.exists())
            targetDir.mkdirs();
        File target = new File(targetPath + "/" + fileName);
        FileChannel in = null;
        FileChannel out = null;
        FileInputStream inStream = null;
        FileOutputStream outStream = null;
        try {
            inStream = new FileInputStream(source);
            outStream = new FileOutputStream(target);
            in = inStream.getChannel();
            out = outStream.getChannel();
            in.transferTo(0L, in.size(), out);
        } catch (IOException e) {
            e.printStackTrace();
            try {
                inStream.close();
                in.close();
                outStream.close();
                out.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        } finally {
            try {
                inStream.close();
                in.close();
                outStream.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

4、文件数据操作

/**
     * 根据文件路径删除文件
     * @param filePath 待删除文件路径  /data/website/abc.txt
     */
    public static void delFile(String filePath) {
        File f = new File(filePath);
        f.delete();
    }

    /**
     * 在指定文件夹中删除指定后缀文件
     * @param filePath 指定文件夹路径 /data/website/
     * @param suffix 文件后缀 .txt
     */
    public static void delSuffixFile(String filePath, String suffix) {
        File dir = new File(filePath);
        File[] fs = dir.listFiles();
        for (File f : fs) {
            if (!f.getName().endsWith(suffix))
                continue;
            f.delete();
        }
    }

    /**
     * 获取文件名 
     * @param filePath /data/website/abc.txt
     * @return 文件名 abc.txt
     */
    public static String fileName(String filePath) {
        File f = new File(filePath);
        return f.getName();
    }

    /**
     * 获取文件父目录
     * @param filePath  /data/website/abc.txt
     * @return 文件父目录 /data/website/
     */
    public static String dirpath(String filePath) {
        File f = new File(filePath);
        String path = "";
        if (f.isFile())
            path = filePath.substring(0, filePath.indexOf(f.getName()));
        return path;
    }

    /**
     * 删除文件夹
     * @param filePath 待删除的文件夹 /data/website/
     */
    public static void delDir(String filePath) {
        if (!filePath.endsWith(File.separator))
            filePath = filePath + File.separator;
        File dirFile = new File(filePath);
        if ((!dirFile.exists()) || (!dirFile.isDirectory()))
            return;
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++)
            if (files[i].isFile())
                delFile(files[i].getAbsolutePath());
            else
                delDir(files[i].getAbsolutePath());
        dirFile.delete();
    }

    /**
     * 重命名文件
     * @param resFilePath 待重命名文件 /data/website/abc.txt
     * @param newFileName 新文件名 abcd.txt
     * @return 
     */
    public static boolean renameFile(String resFilePath, String newFileName) {
        File f = new File(resFilePath);
        String newFilePath = f.getParent() + File.separator + newFileName;
        File resFile = new File(resFilePath);
        File newFile = new File(newFilePath);
        return resFile.renameTo(newFile);
    }

5、读文件的内容

/**
     * 读取文本内容 为String
     * @param filePath /data/website/abc.txt
     * @return
     * @throws IOException
     */
    public static String readFileContent(String filePath) throws IOException {
        return readFileContent(filePath, null, null, 1024);
    }

    /**
     * 根据指定编码读取内容 
     * @param filePath /data/website/abc.txt
     * @param encoding UTF-8/GB2312...
     * @return
     * @throws IOException
     */
    public static String readFileContent(String filePath, String encoding) throws IOException {
        return readFileContent(filePath, encoding, null, 1024);
    }

    /**
     * 设置缓冲区大小 读取文本内容
     * @param filePath /data/website/abc.txt
     * @param bufLen 缓冲区大小 默认1024
     * @return
     * @throws IOException
     */
    public static String readFileContent(String filePath, int bufLen) throws IOException {
        return readFileContent(filePath, null, null, bufLen);
    }

    /**
     * 设置编码 换行符 读取文件内容
     * @param filePath /data/website/abc.txt
     * @param encoding
     * @param sep 换行符 默认\n
     * @return
     * @throws IOException
     */
    public static String readFileContent(String filePath, String encoding, String sep) throws IOException {
        return readFileContent(filePath, encoding, sep, 1024);
    }

    /**
     * 设置编码方式 换行符 缓冲区大小 读取文本内容
     * @param filePath /data/website/abc.txt
     * @param encoding UTF-8/GB2312...
     * @param sep 换行符 默认\n
     * @param bufLen 缓冲区 默认1024
     * @return
     * @throws IOException
     */
    public static String readFileContent(String filePath, String encoding, String sep, int bufLen) throws IOException {
        if ((filePath == null) || (filePath.equals("")))
            return "";
        if ((sep == null) || (sep.equals("")))
            sep = "\n";
        if (!new File(filePath).exists())
            return "";
        StringBuffer str = new StringBuffer("");
        FileInputStream fs = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            fs = new FileInputStream(filePath);
            if ((encoding == null) || (encoding.trim().equals("")))
                isr = new InputStreamReader(fs);
            else
                isr = new InputStreamReader(fs, encoding.trim());
            br = new BufferedReader(isr, bufLen);
            String data = "";
            while ((data = br.readLine()) != null)
                str.append(data).append(sep);
        } catch (IOException e) {
            throw e;
        } finally {
            try {
                if (br != null)
                    br.close();
                if (isr != null)
                    isr.close();
                if (fs != null)
                    fs.close();
            } catch (IOException e) {
                throw e;
            }
        }
        return str.toString();
    }

6、向文件中写入内容

/**
     * 在指定目录创建指定文件名文件 并写入内容
     * @param path /data/website/
     * @param fileName abc.txt
     * @param content 文件内容
     * @return
     * @throws IOException
     */
    public static boolean newFile(String path, String fileName, StringBuffer content) throws IOException {
        return newFile(path, fileName, content, 1024, false);
    }

    /**
     * 在指定目录创建指定文件名文件 并写入内容 是否追加写入内容
     * @param path /data/website/
     * @param fileName abc.txt
     * @param content 文件内容
     * @param isWrite 是否追加内容
     * @return
     * @throws IOException
     */
    public static boolean newFile(String path, String fileName, StringBuffer content, boolean isWrite)
            throws IOException {
        return newFile(path, fileName, content, 1024, isWrite);
    }

    /**
     * 在指定目录创建指定文件名文件 设置缓冲区 并写入内容 是否追加写入内容
     * @param path /data/website/
     * @param fileName abc.txt
     * @param content 文件内容
     * @param bufLen 写文件缓冲器
     * @param isWrite 是否追加内容
     * @return
     * @throws IOException
     */
    public static boolean newFile(String path, String fileName, StringBuffer content, int bufLen, boolean isWrite)
            throws IOException {
        if ((path == null) || (path.equals("")) || (content == null) || (content.equals("")))
            return false;
        boolean flag = false;
        FileWriter fw = null;
        BufferedWriter bw = null;
        File file = new File(path);
        if (!file.exists())
            file.mkdirs();
        try {
            fw = new FileWriter(path + File.separator + fileName, isWrite);
            bw = new BufferedWriter(fw, bufLen);
            bw.write(content.toString());
            flag = true;
        } catch (IOException e) {
            System.out.println("写入文件出错");
            flag = false;
            throw e;
        } finally {
            if (bw != null) {
                bw.flush();
                bw.close();
            }
            if (fw != null)
                fw.close();
        }
        return flag;
    }

    /**
     * 创建文件 并覆盖内容
     * @param path /data/website/
     * @param fileName abc.txt
     * @param content 内容
     * @return
     * @throws IOException
     */
    public static boolean newFile(String path, String fileName, String content) throws IOException {
        return newFile(path, fileName, content, 1024, false);
    }

    /**
     * 设置是否追加 
     * @param path /data/website/
     * @param fileName abc.txt
     * @param content 内容
     * @param isWrite 是否追加内容
     * @return
     * @throws IOException
     */
    public static boolean newFile(String path, String fileName, String content, boolean isWrite) throws IOException {
        return newFile(path, fileName, content, 1024, isWrite);
    }

    /**
     * 设置缓冲区大小 是否追加内容 
     * @param path /data/website/
     * @param fileName abc.txt
     * @param content 内容
     * @param bufLen 缓冲区大小
     * @param isWrite 是否追加内容
     * @return
     * @throws IOException
     */
    public static boolean newFile(String path, String fileName, String content, int bufLen, boolean isWrite)
            throws IOException {
        if ((path == null) || (path.equals("")) || (content == null) || (content.equals("")))
            return false;
        boolean flag = false;
        FileWriter fw = null;
        BufferedWriter bw = null;
        File file = new File(path);
        if (!file.exists())
            file.mkdirs();
        try {
            fw = new FileWriter(path + File.separator + fileName, isWrite);
            bw = new BufferedWriter(fw, bufLen);
            bw.write(content);
            flag = true;
        } catch (IOException e) {
            System.out.println("写入文件出错");
            flag = false;
            throw e;
        } finally {
            if (bw != null) {
                bw.flush();
                bw.close();
            }
            if (fw != null)
                fw.close();
        }
        return flag;
    }

    /**
     * 创建文件目录 支持多层目录创建
     * @param filePath /data/website/
     * @return
     * @throws Exception
     */
    public static boolean newFolder(String filePath) throws Exception {
        boolean flag = false;
        if ((filePath == null) || (filePath.equals("")) || (filePath.equals("null")))
            return flag;
        try {
            File myFilePath = new File(filePath);
            if (!myFilePath.exists())
                myFilePath.mkdirs();
            flag = true;
        } catch (Exception e) {
            throw e;
        }
        return flag;
    }
    /**
     * 拷贝文件 
     * @param sourcePath /data/website/abc.txt
     * @param targetPath 目标目录
     * @return
     * @throws IOException
     */
    public static boolean copyFile(String sourcePath, String targetPath) throws IOException {
        return copyFile(sourcePath, targetPath, null);
    }

    /**
     * 拷贝文件  指定新的文件名
     * @param oldPath /data/website/abc.txt
     * @param newPath 新目录 /data/website2/
     * @param newFileName abcd.txt
     * @return
     * @throws IOException
     */
    public static boolean copyFile(String oldPath, String newPath, String newFileName) throws IOException {
        boolean flag = false;
        if ((oldPath == null) || (newPath == null) || (newPath.equals("")) || (oldPath.equals("")))
            return flag;
        InputStream inStream = null;
        FileOutputStream fs = null;
        try {
            int bytesum = 0;
            int byteread = 0;
            File file = null;
            file = new File(newPath);
            if (!file.exists())
                file.mkdirs();
            file = new File(oldPath);
            if (file.exists()) {
                inStream = new FileInputStream(oldPath);
                if ((newFileName == null) || (newFileName.equals("")))
                    newFileName = file.getName();
                fs = new FileOutputStream(newPath + File.separator + newFileName);
                byte[] buffer = new byte[8192];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread;
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                flag = true;
            }
        } catch (IOException e) {
            throw e;
        } finally {
            try {
                if (fs != null)
                    fs.close();
                if (inStream != null)
                    inStream.close();
            } catch (IOException e) {
                throw e;
            }
        }
        return flag;
    }

    /**
     * 拷贝文件夹
     * @param oldPath 源文件夹 /data/website/
     * @param newPath 目标文件夹 /data/website2/
     * @throws Exception
     */
    public static void copyFolder(String oldPath, String newPath) throws Exception {
        if ((oldPath == null) || (newPath == null) || (newPath.equals("")) || (oldPath.equals("")))
            return;
        FileInputStream input = null;
        FileOutputStream output = null;
        try {
            File temp = null;
            temp = new File(newPath);
            if (!temp.exists())
                temp.mkdirs();
            temp = new File(oldPath);
            String[] file = temp.list();
            for (int i = 0; i < file.length; i++) {
                if (oldPath.endsWith(File.separator))
                    temp = new File(oldPath + file[i]);
                else
                    temp = new File(oldPath + File.separator + file[i]);
                if (temp.isFile()) {
                    input = new FileInputStream(temp);
                    output = new FileOutputStream(newPath + File.separator + temp.getName().toString());
                    byte[] b = new byte[8192];
                    int len;
                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                }
                if (!temp.isDirectory())
                    continue;
                copyFolder(oldPath + File.separator + file[i], newPath + File.separator + file[i]);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (Exception e) {
                throw e;
            }
        }
    }

    /**
     * 移动文件 
     * @param srcFile /data/website2/abc.txt
     * @param destPath /data/website/
     * @return
     */
    public static boolean Move(String srcFile, String destPath) {
        return Move(srcFile, destPath, null);
    }

    /**
     * 移动文件  指定新文件名
     * @param srcFile 源文件 /data/website2/abc.txt
     * @param destPath 目标文件夹 /data/website/
     * @param newFileName abcd.txt
     * @return
     */
    public static boolean Move(String srcFile, String destPath, String newFileName) {
        boolean flag = false;
        if ((srcFile == null) || (srcFile.equals("")) || (destPath == null) || (destPath.equals("")))
            return flag;
        File file = new File(srcFile);
        File dir = new File(destPath);
        if ((newFileName == null) || (newFileName.equals("")) || (newFileName.equals("null")))
            newFileName = file.getName();
        flag = file.renameTo(new File(dir, newFileName));
        return flag;
    }

    /**
     * 剪切功能
     * @param oldPath 源文件  /data/website/abc.txt
     * @param newPath 目标文件  /data/website2/abc.txt
     * @throws Exception
     */
    public static void moveFile(String oldPath, String newPath) throws Exception {
        if (copyFile(oldPath, newPath))
            delFile(oldPath);
    }

    /**
     * 剪切功能
     * @param oldPath 源文件  /data/website/abc.txt
     * @param newPath 目标文件目录  /data/website2/
     * @param newFileName 新文件名 abc.txt
     * @throws Exception
     */
    public static void moveFile(String oldPath, String newPath, String newFileName) throws Exception {
        if (copyFile(oldPath, newPath))
            delFile(oldPath);
    }

    /**
     * 剪切文件夹
     * @param oldPath 源目录 /data/website/
     * @param newPath 目标目录 /data/website2/
     * @throws Exception
     */
    public static void moveFolder(String oldPath, String newPath) throws Exception {
        copyFolder(oldPath, newPath);
        delFolder(oldPath);
    }

    /**
     * 删除文件夹
     * @param folderPath 待删除文件目录 /data/website2/
     */
    public static void delFolder(String folderPath) {
        if ((folderPath == null) || (folderPath.equals("")))
            return;
        try {
            File myFilePath = new File(folderPath);
            if ((myFilePath.isDirectory()) && (myFilePath.exists())) {
                delAllFile(folderPath);
                myFilePath.delete();
            }
        } catch (Exception e) {
            System.out.println("删除文件夹操作出错");
            e.printStackTrace();
        }
    }

    /**
     * 删除指定目录下的所有文件
     * @param path /data/website/
     */
    public static void delAllFile(String path) {
        if ((path == null) || (path.equals("")))
            return;
        File file = new File(path);
        if ((!file.exists()) || (!file.isDirectory()))
            return;
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator))
                temp = new File(path + tempList[i]);
            else
                temp = new File(path + File.separator + tempList[i]);
            if (temp.isFile())
                temp.delete();
            if (!temp.isDirectory())
                continue;
            delAllFile(path + File.separator + tempList[i]);
            delFolder(path + File.separator + tempList[i]);
        }
    }

    public static void del(String filepath) throws Exception {
        if ((filepath == null) || (filepath.equals("")) || (filepath.equals("null")))
            return;
        try {
            File f = new File(filepath);
            if ((f.exists()) && (f.isDirectory())) {
                if (f.listFiles().length == 0) {
                    f.delete();
                } else {
                    File[] delFile = f.listFiles();
                    int i = f.listFiles().length;
                    for (int j = 0; j < i; j++) {
                        if (delFile[j].isDirectory())
                            del(delFile[j].getAbsolutePath());
                        delFile[j].delete();
                    }
                }
                del(filepath);
            }
        } catch (Exception e) {
            throw e;
        }
    }

    public static String read(String fileName, String encoding) {
        File f = new File(fileName);
        if (!f.exists())
            return null;
        StringBuffer fileContent = new StringBuffer();
        try {
            FileInputStream fis = new FileInputStream(fileName);
            InputStreamReader isr = new InputStreamReader(fis, encoding);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                fileContent.append(line);
                fileContent.append(System.getProperty("line.separator"));
            }
            br.close();
            isr.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileContent.toString();
    }

    /**
     * 写文件
     * @param fileContent 文件内容
     * @param filePath 文件地址 包括文件名信息
     * @param encoding 编码方式
     */
    public static void write(String fileContent, String filePath, String encoding) {
        try {
            FileOutputStream fos = new FileOutputStream(filePath);
            OutputStreamWriter osw = new OutputStreamWriter(fos, encoding);
            osw.write(fileContent);
            osw.flush();
            osw.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
	 * 写TXT文件工具类
	 * @param file 需要写的文件
	 * @param conent 内容
	 * @param append 是否拼接 true 拼接 false 不拼接
	 * @param charset 编码 例如:utf-8、gbk...
	 */
	public static void writeTxt(File file, String conent ,boolean append,String charset) {
		if(!file.exists())
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		BufferedWriter out = null;
		try {
				out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,append)));
				out.write(conent);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 
	 * 写TXT文件工具类
	 * @param file 需要写的文件
	 * @param conent 内容
	 * @param append 是否拼接 true 拼接 false 不拼接
	 * @param charset 编码 例如:utf-8、gbk...
	 */
	public static void writeTxt(String file, String conent ,boolean append,String charset) {
		File f = new File(file);
		if(!f.exists())
			try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		writeTxt(f , conent ,append , charset);
	}
	/**
	 * 
	 * 写TXT文件工具类 默认utf8
	 * @param file 需要写的文件
	 * @param conent 内容
	 * @param append 是否拼接 true 拼接 false 不拼接
	 */
	public static void writeTxt(String file, String conent ,boolean append)
	{
		writeTxt(file,conent,append,"utf-8");
	}
	
	/**
	 * 
	 * 写TXT文件工具类 默认utf8 拼接
	 * @param file 需要写的文件
	 * @param conent 内容
	 */
	public static void writeTxt(String file, String conent )
	{
		writeTxt(file,conent,true, "utf-8");
	}
	
    /*public static void main(String[] args) {
        System.out.println(fileName("c:\\1.log"));
    }*/
    /**
	 * 
	 * @param dir 文件夹目录
	 * @param fileName 文件名
	 * @param conent
	 * @param append
	 * @param charset
	 */
	public static void writeTxt(String dir,String fileName, String conent ,boolean append,String charset) {
		File dirFile = new File(dir);
		if(!dirFile.exists())
			dirFile.mkdirs();
		File f = new File(dir + fileName);
		if(!f.exists())
			try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		
		BufferedWriter out = null;
		try {
				out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f,append),Charset.forName(charset)));
				out.write(conent);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

7、远程请求处理(http,soap)

public static String doGet(String url, Map<String, String> param) throws Exception {
		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();
		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build();

			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);

			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), ENCODING);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
				throw e;
			}
		}
		return resultString;
	}

	public static String doGet(String url) throws Exception {
		return doGet(url, null);
	}

	public static String doPost(String url, Map<String, String> param) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建参数列表
			if (param != null) {
				List<NameValuePair> paramList = new ArrayList<>();
				for (String key : param.keySet()) {
					paramList.add(new BasicNameValuePair(key, param.get(key)));
				}
				// 模拟表单
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, ENCODING);
				httpPost.setEntity(entity);
			}
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), ENCODING);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	public static String doPost(String url) {
		return doPost(url, null);
	}

	public static String doPostJson(String url, String json) {
		return doPostJson(url, null, json);
	}

	/**
	 * 功能:后台交易提交请求报文并接收同步应答报文<br>
	 * @param reqData 请求报文<br>
	 * @param reqUrl  请求地址<br>
	 * @param encoding<br>
	 * @return 应答http 200返回true ,其他false<br>
	 */
	public static Map<String,String> post(
			Map<String, String> reqData,String reqUrl,String encoding) {
		Map<String, String> rspData = new HashMap<String,String>();
		LogUtil.writeLog("请求银联地址:" + reqUrl);
		//发送后台请求数据
		HttpClient hc = new HttpClient(reqUrl, 30000, 30000);//连接超时时间,读超时时间(可自行判断,修改)
		try {
			int status = hc.send(reqData, encoding);
			if (200 == status) {
				String resultString = hc.getResult();
				if (null != resultString && !"".equals(resultString)) {
					// 将返回结果转换为map
					Map<String,String> tmpRspData  = SDKUtil.convertResultStringToMap(resultString);
					rspData.putAll(tmpRspData);
				}
			}else{
				LogUtil.writeLog("返回http状态码["+status+"],请检查请求报文或者请求地址是否正确");
			}
		} catch (Exception e) {
			LogUtil.writeErrorLog(e.getMessage(), e);
		}
		return rspData;
	}

	// 这个要弄长点
    public static final  int TIMEOUT = 60;
    public static final String ACCEPT_NAME = "Accept";
    public static final String ACCEPT = "application/json;charset=UTF-8";

    /**
	 * 请求的参数类型为json
	 *
	 * @param url
	 * @param json
	 * @return {username:"",pass:""}
	 */
	public static String doPostJson(String url, Map<String, String> headerMap, String json) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {

            RequestConfig defaultRequestConfig = RequestConfig.custom()
                    .setSocketTimeout(TIMEOUT * 1000)
                    .setConnectTimeout(TIMEOUT * 1000)
                    .setConnectionRequestTimeout(TIMEOUT * 1000)
                    .build();

			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);

            httpPost.setProtocolVersion(HttpVersion.HTTP_1_0);
            httpPost.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
            httpPost.addHeader(ACCEPT_NAME, ACCEPT);
            httpPost.setConfig(defaultRequestConfig);

            if (headerMap != null) {
				Iterator headerIterator = headerMap.entrySet().iterator(); // 循环增加header
				while (headerIterator.hasNext()) {
					Entry<String, String> elem = (Entry<String, String>) headerIterator.next();
					httpPost.addHeader(elem.getKey(), elem.getValue());
				}
			}

			// 创建请求内容
			StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
			httpPost.setEntity(entity);
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), ENCODING);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	/**
	 * 请求的参数类型为xml,支持SOAP1.2
	 *
	 * @param url
	 * @param xml
	 *
	 * @return {username:"",pass:""}
	 */
	public static String doPostXml(String url, String xml, String soapname) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 设置SOAPAction,支持soap1.2
			httpPost.setHeader("SOAPAction", soapname);
			// 创建请求内容
			StringEntity entity = new StringEntity(xml, ContentType.TEXT_XML);
			httpPost.setEntity(entity);
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), ENCODING);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	/**
	 * 请求的参数类型为xml
	 *
	 * @param url
	 * @param xml
	 * @return {username:"",pass:""}
	 */
	public static String doPostXml(String url, String xml) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建请求内容
			StringEntity entity = new StringEntity(xml, ContentType.TEXT_XML);
			httpPost.setEntity(entity);
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), ENCODING);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	public static String doPostWebservice(String url, String xml) throws Exception {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
			StringEntity data = new StringEntity(xml, Charset.forName("UTF-8"));
			httpPost.setEntity(data);
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), ENCODING);
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}
	
	/**
	 *该方法适用于调用:使用SOAP1.1协议的webService服务
	 *
	 */
	public static String doPostWebserviceForSoap11(String url, String xml,String SOAPAction) throws Exception {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
			httpPost.setHeader("SOAPAction",SOAPAction);
			StringEntity data = new StringEntity(xml, Charset.forName("UTF-8"));
			httpPost.setEntity(data);
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), ENCODING);
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	public static String doPostRequest(String url,String xml) {
		return doPostRequest(url,xml,"");
	}


	public static String doPostRequest(String url,String xml,String SOAPAction) {
		String result = "";
		Map<String, String> requestPropertyMap = new HashMap<>();
		requestPropertyMap.put("Content-Type", "text/xml;charset=UTF-8");
		requestPropertyMap.put("SOAPAction", SOAPAction);
		if ((url == null) || ("".equals(url)))
			return result;
		try {
			URL httpurl = new URL(url);
			HttpURLConnection httpConn = (HttpURLConnection) httpurl
					.openConnection();
			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);
			for(Map.Entry<String, String> entry : requestPropertyMap.entrySet()) {
				httpConn.setRequestProperty(entry.getKey(), entry.getValue());
			}

			httpConn.setRequestMethod("POST");
			PrintWriter out = new PrintWriter(httpConn.getOutputStream());
			out.print(xml);
			out.flush();
			out.close();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					httpConn.getInputStream(), "utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result = result + line;
			}
			in.close();
		} catch (Exception e) {
			System.out.println(e);
		}
		return result;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

深漂的小小小刘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值