分类:技术交流

没有分类的技术文章

LINUX服务器上配置wildfly10 && maven

LINUX服务器上配置wildfly10 && maven

一、下载/传输 tar.gz包 到服务器

在本地Linux

  1. 到官网http://wildfly.org/下载对应版本,然后
  2. # scp wildfly-10.1.0.Final.tar.gz user_name@120.64.xx.xxx:/usr/local/wildfly

或者直接在服务器端

  1. # wget http://download.jboss.org/wildfly/10.1.0.Final/wildfly-10.1.0.Final.tar.gz

 

二、安装配置wildfly

  1. 解压缩
  2. # tar zxf wildfly-10.1.0.Final.tar.gz
  3. 添加系统管理用户
  4. # cd bin/
  5. # ./add-user.sh
  6. 按照提示步骤建立用户(admin)
  7. 修改配置文档,使其对全网开放
  8. # vi /usr/local/wildfly/wildfly-10.1.0.Final/standalone/configuration/standalone.xml
  9. 将文件尾部 bind    127.0.0.1 修改为0.0.0.0
  10. 启动服务器
  11. # ./standalone.sh

三、下载-安装-配置 maven

  1. 下载
  2. # cd /usr/local/maven
  3. # wget http://mirrors.hust.edu.cn/apache/maven/maven-3/3.5.0/binaries/apache-maven-3.5.0-bin.tar.gz
  1. 安装配置
  2. # tar zxf  apache-maven-3.5.0-bin.tar.gz
  3. # vi /etc/profile
  4. 在尾部添加
  5. export MAVEN_HOME=/usr/local/apache-maven-3.5.0
  6. export PATH=$PATH:$MAVEN_HOME/bin
  7. # source /etc/profile
  8. # mvn -v

Apache Maven 3.5.0 (ff8f5e7444045639af65f6095c62210b5713f426; 2017-04-04T03:39:06+08:00)
Maven home: /usr/local/maven/apache-maven-3.5.0
Java version: 1.8.0_121, vendor: Oracle Corporation
Java home: /usr/java/jdk1.8.0_121/jre
Default locale: zh_CN, platform encoding: UTF-8
OS name: “linux”, version: “2.6.32-642.13.1.el6.x86_64”, arch: “amd64”, family: “unix”

 

注意,wildfly10需要JDK1.8的支持

Nginx基础配置

Nginx基础配置

 

总线错误和内存地址对齐

总线错误和内存地址对齐

我们在编写c语言程序的时候,应该都碰到过段错误的问题,我也不例外,不过我在前几天遇到了一个新问题,就是总线错误,百度了一下

总线错误的原因基本上就是由于地址的不对齐,所谓地址的不对齐,意思就是在计算机分配地址的时候,给整型数据(占4个字节)或者是double型数据(占8个字节)必须给予他们分配4或者8的倍数,并且一次读取4或者8的倍数的数据,这样能够最大化的提高计算机的读取效率,例如说

说一下结构体和联合在计算机中的存储方式

结构体的存储:

第一个结构成员占据下标为0的位置,剩下的以此往后排,int型占据4个位置,double占8个,就想这样

当结构体作为结构成员时,起存储方式按照最大成员的整数倍来存储

这就是所谓的内存地址对齐,按照最一开始的代码赋给那个联合的地址准确来说没错,只是让计算机的效率降低了,在读取这个地址的时候只能先按照4的4的整数倍读取地址,然后计算机再做处理

利用hibernate生成UUID工具类 (用来生成随机序列号,常用来保存字段主键的值)

利用hibernate生成UUID工具类 (用来生成随机序列号,常用来保存字段主键的值)

 

package beckey.util;

import org.hibernate.id.IdentifierGenerator;
import org.hibernate.id.UUIDHexGenerator;

/**
*
* 功能说明:UUID 生成工具类
*/
public class UUIDGenerator {
private static int count=0;
public static String javaId(){
count++;
String resultId=””+System.currentTimeMillis()+””+count;
if(count>=90){
count=0;
}
return resultId;
}
/**
* hibernate id生成器
* @return
*/
public static String hibernateUUID(){
IdentifierGenerator gen = new UUIDHexGenerator();
String id = (String) gen.generate(null, null);
return id;
}
public static void main( String[] args ) throws Exception {
String id=javaId();
System.out.println(id);;
}
}

 

Postgresql 9.5的事务隔离级别

Postgresql 9.5的事务隔离级别

事务隔离级别的概念

试验验证

2.1 read uncommitted

  1. 在终端1执行以下命令,开始一个read uncommitted事务:

  2. 在终端2执行以下命令,开始一个read uncommitted事务:

  3. 在终端2查询salary数据表的内容,目前没有数据:

  4. 在终端1插入数据到salary:

  5. 在终端2查询salary数据表的内容,依然是空的

  6. 在终端1执行commit命令提交事务:

  7. 再次在终端2查询salary数据表的内容:

2.2 read committed

2.3 repeatable read

  1. 在终端1开启一个reapable read事务1:

  2. 在终端2开启一个reapable read事务2:

  3. 检查事务2中salary表的当前内容:

  4. 在事务1中插入一些数据:

  5. 在事务2中检查salary表的当前内容,看不到在事务1中新插入的数据:这很正常,repeatable read的隔离级别比read committed还要高,即便在read committed隔离级别中,也不应该看到事务1中还没有提交的内容,更何况repeatable read呢:

  6. 在事务1中提交并结束事务:

  7. 在事务2中检查salary表的内容,依然看不到在事务1中插入的数据,即便事务1已经提交了!这是重点:

  8. 在终端1中再次插入数据(默认是read committed事务隔离级别),此时在终端1我们可以看到salary表已经有4条记录了:

  9. 在事务2中检查salary表的当前内容,没有意外的,依然只能看到一条记录,即事务2开启时salary表是什么状态,在事务2的整个执行过程中,salary的状态保持不变,这样无论在事务2中执行多少次select查询,每次得到的结果都是一致的,并不受其他事务的任何影响,这就是repeatable read的含义。
  10. 在事务2中如果只是执行select查询的话,repeatable read是完美的。但是,如果在事务2中要更新数据,会发生什么情况呢?我们首先在终端1中更新一下数据,制造一点小麻烦,即在事务2中看到的数据和事务1中看到的数据是不一致的:

  11. 此时,在事务2中看到的salary表的id=1的记录中,money字段其实是1000,事务2并不知道在另外的事务中已经把这个数字修改成了2000了。我们在事务2中企图也更新这个数字,可以看到在事务2中的这个命令会一直等待下去,也就是说,因为我们在其他事务中已经更新了这条记录,事务2中的更新命令只能等待其他事务结束后才能继续执行:

  12. 在事务1中提交事务:

  13. 我们看到在事务2中显示出错信息:

2.4 serializable

对象锁

如何使用秘钥链接github和gogs

如何使用秘钥链接github和gogs

如何使用秘钥链接github

一、首先解决https和ssh的区别

1.1 设置ssh的原因

我们在用github管理项目的时候,可以使用https url克隆到本地,也可以使用 SSH url 克隆到本地。使用https url克隆对初学者来说会比较方便,复制https url 然后到 git Bash 里面直接用clone命令克隆到本地就好了,而使用 SSH url 克隆却需要在克隆之前先配置和添加好 SSH key 。

因此,如果你想要使用 SSH url 克隆的话,你必须是这个项目的拥有者。否则你是无法添加 SSH key 的。

1.2 二者区别

(1)、前者可以随意克隆github上的项目,而不管是谁的;而后者则是你必须是你要克隆的项目的拥有者或管理员,又因为我们的本地Git仓库和GitHub仓库之间的传输是通过SSH加密的,所以,需要先添加 SSH key ,否则无法克隆。

(2)、https url 在push的时候是需要验证用户名和密码的;而 SSH 在push的时候,是不需要输入用户名的,如果配置SSH key的时候设置了密码,则是需要输入密码的,否则直接是不需要输入密码的。

二、在github上添加ssh key的步骤

第1步 秘钥对——两个文件

2.1.1检查你是否有.ssh目录,它在你的主目录下

2.1.2如果你的主目录下有.ssh目录,查看旗下的两个文件:id_rsa和id_rsa.pub。这就是ssh的秘钥对,前者为私钥,当然不可泄露,后者为公钥。如果没有,打开Shell(Windows下打开Git Bash),创建SSH Key:

命令行如下:

$ ssh-keygen -t rsa -C “youremail@example.com”

个人演示如下:

gaohan@gaohan-Lenovo-G50-70:~$ gaohan@gaohan-Lenovo-G50-70:~/桌面$ ssh-keygen -t rsa -C “youremail@example.com”

你需要把邮件地址换成你自己的邮件地址,然后一路回车(鉴于我个人已经有了这个目录就不在此演示了)使用默认值即可,由于这个Key也不是用于军事目的,所以也无需设置密码。
第2步 添加ssh到github上去

2.2.1登陆github;

2.2.2打开Settings(位于右上角);

2.2.3点击SSH Keys界面;

2.2.4创建SSH Keys(点击New SSH key);

2.2.5填上任意Tile;

2.2.6在Key文本框粘贴id_rsa.pub文件中的内容(复制粘贴上就可);

2.2.7最后点击Add Key,然后就会看到你添加的Key了。

第3步 测试一下你的SSH Key

2.3.1在你的终端输入一下代码

gaohan@gaohan-Lenovo-G50-70:~$ ssh -T git@github.com

紧接着出现一段警告

The authenticity of host ‘github.com (192.30.252.131)’ can’t be established.

RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8.

Are you sure you want to continue connecting (yes/no)? yes

选择yes(注意不是y!)

当出现一下内容时,就算是大功告成了。

Warning: Permanently added ‘github.com,192.30.252.131’ (RSA) to the list of known hosts.

Hi gaohanyagapohan! You’ve successfully authenticated, but GitHub does not provide shell access.

如何使用秘钥链接gogs

这一个的步骤和github基本一样,在这就不作解释

wordpress中的代码加亮

wordpress中的代码加亮

在wordpress安装crayon syntax lighter 这个插件后的显示效果如下:

 

看起来还不错!用法是在编辑文章界面点击下图圈起来的那个图标即可:

crayon-syntax-lighter-toolbar

StringUtils工具类

StringUtils工具类

package com.hollycrm.hollycore.service.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressWarnings(“unchecked”)
public class StringUtil extends StringUtils {
public static String rootpath = “”;

private static final char QUOTE_ENCODE[] = “"”.toCharArray();
private static final char AMP_ENCODE[] = “&”.toCharArray();
private static final char LT_ENCODE[] = “<”.toCharArray();
private static final char GT_ENCODE[] = “>”.toCharArray();
private static final int fillchar = 61;
private static final String cvt =
“ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/”;
private static Random randGen = new Random();
private static char numbersAndLetters[] =
“0123456789abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ”.
toCharArray();
private static final char zeroArray[] =
“0000000000000000000000000000000000000000000000000000000000000000”.
toCharArray();

static private StringUtil instance;

public StringUtil() {
}

//创建实例
public static synchronized StringUtil getInstance() {
if (instance == null) {
instance = new StringUtil();
}
return instance;
}

/**
* 判断字串desc是否存在于source,存在则返回true,不存在返回false
*
* @param source
* @param desc
* @return
*/
public static boolean inStr(String source, String desc) {
if (source.indexOf(desc) >= 0) {
return true;
} else {
return false;
}
}

/**
* 字符串内码转换–用于从数据库读取数据时
*
* @param source
* @param charset
* @return
*/
public static String decodeGB(String source, String charset) {
try {
return (new String(source.getBytes(charset), “GB2312”));
} catch (Exception E) {
return source;
}
}

/**
* 转换为GBK编码
*
* @param source
* @return
*/
public static String decodeGB(String source) {
try {
return new String(source.getBytes(“ISO8859-1”), “GBK”);
} catch (Exception E) {
return source;
}

}

/**
* 字符串内码转换–用于写入数据库时
*
* @param source
* @param charset
* @return
*/
public static String encodeGB(String source, String charset) {
try {
return (new String(source.getBytes(“GB2312”), charset));
} catch (Exception e) {
return source;
}
}

public static String encodeGB(String source) {
try {
return (new String(source.getBytes(“GBK”), “ISO8859-1”));
} catch (Exception E) {
return source;
}
}

/**
* 替换source中的str1为str2
*
* @param source
* @param str1
* @param str2
* @return
*/
public static String replace(String source, char str1, String str2) {
if (source == null) {
return source;
}
String desc = “”;
for (int i = 0; i < source.length(); i++) {
if (source.charAt(i) == str1) {
desc = desc + str2;
} else {
desc = desc + String.valueOf(source.charAt(i));
}
}
return desc;
}

/**
* 替换source中的str1为str2
*
* @param source
* @param str1
* @param str2
* @return
*/
public static String replace(String source, String str1, String str2) {
if (source == null) {
return source;
}
String desc = “”;
int i = 0;
while (i < source.length()) {
if (source.startsWith(str1, i)) {
desc = desc + str2;
i = i + str1.length();
} else {
desc = desc + String.valueOf(source.charAt(i));
i++;
}

}
return desc;
}

/**
* 判断字符串是否为空
*
* @param s
* @return 是否为空
*/
public static boolean isNullStr(String s) {
if (s == null || s.trim().length() <= 0) {
return true;
} else {
return false;
}
}

/**
* 将Object对象转变为String类型对象,对于null值返回空字符串.
*
* @param inObj 待处理的对象.
*/
public static String killNull(Object inObj) {
if (inObj == null) {
return “”;
}
return inObj.toString().trim();
}

/**
* 将Object对象转变为String类型对象,对于null值返回缺省字符串.
*
* @param inObj 待处理的对象.
*/
public static String killNull(Object inObj, String toStr) {
if (inObj == null) {
return toStr;
}
return inObj.toString().trim();
}

/**
* 从InputStream中获取字符串对象
*
* @param is
* @param charset
* @return
*/
public static String valueOf(InputStream is, String charset) {
String result = null;
if (is != null) {
try {
byte[] buffer = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int l = is.read(buffer);
while (l != -1) {
baos.write(buffer, 0, l);
l = is.read(buffer);
}
is.close();
result = new String(baos.toByteArray(), charset);
} catch (Exception ex) {
ex.printStackTrace();
}
}
return result;
}

/**
* 过滤查询条件中的非法字符
*
* @param str
* @return
*/
public static String getFilterString(String str) {
str = str.replace(‘<‘, ‘_’);
str = str.replace(‘>’, ‘_’);
str = str.replace(‘”‘, ‘_’);
str = str.replace(‘\”, ‘_’);
str = str.replace(‘%’, ‘_’);
str = str.replace(‘;’, ‘_’);
str = str.replace(‘(‘, ‘_’);
str = str.replace(‘)’, ‘_’);
str = str.replace(‘&’, ‘_’);
str = str.replace(‘+’, ‘_’);
return str;
}

/**
* 首字母改为大�?
*
* @param str
* @return
*/
public static String firstToUpper(String str) {
str = str.trim();
String ret = “”;
if (str.length() >= 1) {
ret = str.substring(0, 1).toUpperCase() + str.substring(1, str.length());
}
return ret;
}

/**
* 首字母改为小�?
*
* @param str
* @return
*/
public static String firstToLower(String str) {
str = str.trim();
String ret = “”;
if (str.length() >= 1) {
ret = str.substring(0, 1).toLowerCase() + str.substring(1, str.length());
}
return ret;
}

/**
* 将时间转换为parrten2格式
*
* @param t1
* @param parrten
* @param parrten2
* @return
*/
public static String getTime(String t1, String parrten, String parrten2) {
return DateUtils.getTime(t1, parrten, parrten2);
}

/**
* �?测字符串s是否是a-z的字母组�?
*
* @param s
* @return boolean
*/
public static boolean checkString(String s) {
boolean tag = false;
String regex = “\\p{Lower}+?”;
if (s != null && !””.equals(s)) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
tag = m.matches();
}
return tag;
}

/**
* 根据模式regex,对字符串s,进行匹�?
*
* @param s 字符�?
* @param regex 模式
* @return boolean true=符合,false=不符�?
*/
public static boolean checkString(String s, String regex) {
boolean tag = false;
if (s != null && !””.equals(s)) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
tag = m.matches();
}
return tag;
}

/**
* 将字符串转换成数�?
*
* @param s �?转换的字符串
* @return int,若该字符串不是数字,则返回�?1
*/
public static int strToInt(String s) {
int temp;
if (StringUtil.isNumeric(s.trim())) {
temp = Integer.parseInt(s);
} else {
temp = 0;
}
return temp;
}

/**
* 将指定字符串重复count次并返回
*
* @param s
* @param count
* @return
*/
public static String repeat(String s, int count) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < count; i++) {
result.append(s);
}
return result.toString();
}

/**
* 将字符串转换成小�?
*
* @param s
* @return
*/
public static String toLowercase(String s) {
String tag = null;
if (s != null && !s.equals(“”)) {
tag = s.toLowerCase();
}
return tag;
}

/**
* 生成SQL语句
*
* @param tablename 表名
* @param sqlprotasis 条件
* @param columnname 字段�?
* @return 生成的SQL语句
*/
public static String generationSql(String tablename, String sqlprotasis,
String[] columnname) {
StringBuffer bufsql = new StringBuffer(“select “);
for (int i = 0; i < columnname.length; i++) {
if (i == (columnname.length – 1)) {
bufsql.append(columnname[i]);
} else {
bufsql.append(columnname[i] + “,”);
}
}
bufsql.append(” from ” + tablename + sqlprotasis);
return bufsql.toString();
}

/**
* 生成SQL语句
*
* @param tablename 表名
* @param sqlprotasis 条件
* @param columnname 字段�?
* @return 生成的SQL语句
*/
public static String generationSql(int number, String tablename,
String sqlprotasis, String[] columnname) {
StringBuffer bufsql = new StringBuffer(“select top ” + number + ” “);
for (int i = 0; i < columnname.length; i++) {
if (i == (columnname.length – 1)) {
bufsql.append(columnname[i]);
} else {
bufsql.append(columnname[i] + “,”);
}
}
bufsql.append(” from ” + tablename + sqlprotasis);
return bufsql.toString();
}

/**
* 截字符串
*
* @param s 字符�?
* @param n 截的位数
* @return
*/
public static String getNumString(String s, int n) {
String tag;
tag = s;
if (s != null && !s.equals(“”)) {
tag = tag.substring(0, n);
} else {
tag = “”;
}
return tag;
}

/**
* 生成SQL语句
*
* @param tablename 表名
* @param sqlprotasis 条件
* @return SQL语句
*/
public static String generationSql(String tablename, String sqlprotasis) {
StringBuffer bufsql = new StringBuffer(“select “);
bufsql.append(“* from ” + tablename + sqlprotasis);
return bufsql.toString();
}

/**
* 删除某目录下的指定文�?
*
* @param filecatalog 目录列表
* @param filename 文件�? String[]
*/
public static void delFile(String filecatalog, String[] filename) {

File delfile;
String fname = “”, name = “”;
try {
for (int i = 0; i < filename.length; i++) {
name = filename[i];
if (name != null && !name.equals(“”)) {
fname = rootpath + filecatalog + name;
delfile = new File(fname);
if (delfile.exists()) { // 判断文件是否存在
delfile.delete();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 判断字符串是否是数字
*
* @param s
* @return 是数字=true;不是数字=false
*/
public static boolean isNumeric(String s) {
boolean flag = true;
if (s != null && !s.equals(“”)) {
char[] numbers = s.toCharArray();
for (int i = 0; i < numbers.length; i++) {
if (!Character.isDigit(numbers[i])) {
flag = false;
break;
}
}
} else {
flag = false;
}
return flag;
}

/**
* 字符串转化为长整行数�?
*
* @param s
* @return
*/
public static long strToLong(String s) {
long temp = 0;
if (isNumeric(s)) {
temp = Long.parseLong(s);
}
return temp;
}

/**
* 格式化输入文本,使输入和输出表现�?�?
*
* @param input 输入
* @return buf
*/
public static String formatHTML(String input) {
if (input == null || input.length() == 0) {
return input;
}
// 建立�?个Stringbuffer 来处理输入的数据
StringBuffer buf = new StringBuffer(input.length() + 6);
char ch = ‘ ‘;
// 处理非法字符�?
for (int i = 0; i < input.length(); i++) {
ch = input.charAt(i);
if (ch == ‘<‘) {
buf.append(“&lt;”);
continue;
}
if (ch == ‘>’) {
buf.append(“&gt;”);
continue;
}

if (ch == ‘\n’) {
buf.append(“<br>”);
continue;
}
if (ch == ‘\”) {
buf.append(“&acute;”);
continue;
}
if (ch == ‘”‘) {
buf.append(“&quot;”);
continue;
}

if (ch == ‘ ‘) {
buf.append(“&nbsp;”);
continue;
}
buf.append(ch);
}
return buf.toString();
}

/**
* 分割字符�?
*
* @param input 要分割的字符�?
* @return
*/
public static String formatBr(String input) {
if (input == null || input.length() == 0) {
return input;
}
// 建立�?个Stringbuffer 来处理输入的数据
StringBuffer bf = new StringBuffer(“”);
String from = “<>”;
StringTokenizer st = new StringTokenizer(input, from, true);
while (st.hasMoreTokens()) {
String tmp = st.nextToken();
if (tmp != null && tmp.equals(“<“)) {
String tmp2 = st.nextToken().toLowerCase();
if (tmp2.equals(“br”)) {
st.nextToken();
bf = bf.append(“”);
}
} else {
bf.append(tmp);
}
}
return bf.toString();
}

/**
* encode转码
*
* @param str
* @return 非空返回str,为空返�?””
*/
public static String encode(String str) {
try {
if (str != null) {
return (new String(str.getBytes(“iso-8859-1”), “gb2312”));
} else
return “”;
} catch (Exception e) {
return e.toString();
}
}

/**
* @param source �?要替换的StringBuffer
* @param strS 被替换的字符�?
* @param strD 用于替换的字符串
* @return 用strD字符串替换source里面strS字符串,例: replace(new
* String(“kkkk”),”k”,”e”),返�?”eeee”
*/
public static StringBuffer replaceAll(StringBuffer source, String strS,
String strD) {
if (strS == null || strD == null || strS.length() == 0
|| strS.equals(strD))
return source;
int start = 0, offset = 0, tag = 0;
while (source.indexOf(strS, tag) != -1) {
start = source.indexOf(strS, tag);
offset = start + strS.length();
tag = start + strD.length();
source.replace(start, offset, strD);
}
return source;
}

/**
* 根据�?始strStart和strEnd提取包含在source中的这段字符�?
*
* @param source 源StringBuffer
* @param strStart �?始标�?
* @param strEnd 结束标记
* @return 返回提取后的StringBuffer
*/

public static StringBuffer takeString(StringBuffer source, String strStart,
String strEnd) {
int start = source.indexOf(strStart) + strStart.length();
int end = source.indexOf(strEnd);
if ((end > start) && end != -1 && start != -1) {
source = new StringBuffer(source.substring(start, end));
return source;
}
return new StringBuffer();
}

/*
* Function name: dealNull Description: \u8655理空字符�? Input: String str
* Output: 不等於null的String
*/
public static String dealNull(Object str) {
String returnstr = null;
if (str == null) {
returnstr = “”;
} else {
returnstr = str.toString();
}
return returnstr;
}

/**
* Function name: split Description: \u5C07字符串劈\u958B成\u6578\u7D44 Input:
* \u5C07字符串source劈\u958B成\u6578\u7D44div(例子:String TTT[] =
* my_class.split(“aaa:bbb:ccc:ddd”,”:”) ; ) Output: \u6578\u7D44
* (返回值:TTT[0]=”aaa”; TTT[1]=”bbb”; TTT[2]=”ccc”; TTT[3]=”ddd”; )
*/
public static String[] split(String source, String div) {
int arynum = 0, intIdx = 0, intIdex = 0, div_length = div.length();
if (source.compareTo(“”) != 0) {
if (source.indexOf(div) != -1) {
intIdx = source.indexOf(div);
for (int intCount = 1; ; intCount++) {
if (source.indexOf(div, intIdx + div_length) != -1) {
intIdx = source.indexOf(div, intIdx + div_length);
arynum = intCount;
} else {
arynum += 2;
break;
}
}
} else
arynum = 1;
} else
arynum = 0;

intIdx = 0;
intIdex = 0;
String[] returnStr = new String[arynum];

if (source.compareTo(“”) != 0) {

if (source.indexOf(div) != -1) {

intIdx = (int) source.indexOf(div);
returnStr[0] = (String) source.substring(0, intIdx);

for (int intCount = 1; ; intCount++) {
if (source.indexOf(div, intIdx + div_length) != -1) {
intIdex = (int) source
.indexOf(div, intIdx + div_length);

returnStr[intCount] = (String) source.substring(intIdx
+ div_length, intIdex);

intIdx = (int) source.indexOf(div, intIdx + div_length);
} else {
returnStr[intCount] = (String) source.substring(intIdx
+ div_length, source.length());
break;
}
}
} else {
returnStr[0] = (String) source.substring(0, source.length());
return returnStr;
}
} else {
return returnStr;
}
return returnStr;
}

/**
* @param name 待切割的字符�?
* @param c 切割字符串的字符
* @return Strin[]
*/
public static String[] split(String name, char c) {
// Figure out the number of parts of the name (this becomes the size
// of the resulting array).
if (name == null)
return null;
int size = 1;
for (int i = 0; i < name.length(); i++) {
if (name.charAt(i) == c) {
size++;
}
}
String[] propName = new String[size];
// Use a StringTokenizer to tokenize the property name.
StringTokenizer tokenizer = new StringTokenizer(name, String.valueOf(c));
int i = 0;
while (tokenizer.hasMoreTokens()) {
propName[i] = tokenizer.nextToken();
i++;
}
return propName;
}

/**
* 根据文件名获得文件的扩展�?
*
* @param filename
* @return
*/
public static String getExt(String filename) {
if (filename.indexOf(“.”) < 0) {
return filename;
}
String[] strs = split(filename, ‘.’);
return strs[strs.length – 1];
}

/**
* 判断字符串是否包含该字符,如果有好写法,建议替换
*
* @param strs String[]
* @param str String
* @return boolean
*/
public static boolean isInclude(String[] strs, String str) {
if (strs.length == 0 || str == null || str.length() == 0) {
return false;
}
str = str.toLowerCase();
for (int i = 0; i < strs.length; i++) {
if (str.equals(strs[i]))
return true;
}
return false;
}

public static String gbToIso(String str) {
try {
if (str != null && !str.equals(“”)) {
byte[] byteStr = str.getBytes(“gb2312”);
return new String(byteStr, “ISO-8859-1”);
} else
return “”;
} catch (Exception e) {
return str;
}
}

public static String isoToGb(String str) {
try {
if (str != null && !str.equals(“”)) {
byte[] byteStr = str.getBytes(“ISO-8859-1”);
return new String(byteStr, “gb2312”);
} else
return “”;
} catch (Exception e) {
return str;
}
}

public static String isoToUTF8(String str) {
try {
if (str != null && !str.equals(“”)) {
byte[] byteStr = str.getBytes(“ISO-8859-1”);
return new String(byteStr, “UTF-8”);
} else
return “”;
} catch (Exception e) {
return str;
}
}

// 不做任何处理,为了替换招聘的isoToGb
public static String retString(String str) {
return str;
}

public static String singleParameter(String name, String value) {
if (name != null && !””.equals(name)) {
return “&” + name + “=” + value;
}
return “”;
}

// 生成单个字段条件
public static String single1SearchContent(String searchname,
String searchtype, String column) {
if (searchname != null && !””.equals(searchname)) {
if (“1″.equals(searchtype)) {
return ” and ” + column + ” = ‘” + searchname + “‘”;
} else {
return ” and ” + column + ” like ‘%” + searchname + “%'”;
}
}
return “”;
}

// 生成单个字段条件
public static String single2SearchContent(String searchname,
String searchtype, String column) {
if (searchname != null && !””.equals(searchname)) {
if (“1″.equals(searchtype)) {
return ” and ” + column + ” = ‘” + searchname + “‘”;
} else if (“2″.equals(searchtype)) {
return ” and ” + column + ” < ‘” + searchname + “‘”;
} else {
return ” and ” + column + ” > ‘” + searchname + “‘”;
}
}
return “”;
}

public static String GBTounicode(String s) {
StringBuffer ss = new StringBuffer();
for (int i = 0; i < s.length(); ++i) {
ss.append(“\\u” + Integer.toHexString(s.charAt(i)));
}
String temp = new String(ss);
return temp;

}

public static String unicodeToGB(String s) {
StringBuffer sb = new StringBuffer();
StringTokenizer st = new StringTokenizer(s, “\\u”);
while (st.hasMoreTokens()) {
sb.append(st.nextToken());
}
return sb.toString();
}

/**
* 将指定字符串中的指定字符替换成同其对应的Ascii�?
* eg. ‘#’->’$35$’ 其中35�?#的Ascii�?
*
* @param sString 源字符串
* @param sChar 特殊字符
* @return
*/
public static String encodeSpecialChar(String sString, char sChar) {
String sResult = sString;
int iCode = sChar;
sResult = StringUtils.replace(sResult, “” + sChar, “$” + iCode + “$”);
return sResult;
}

public static String encodeSpecialChar(String sString, String sChar) {
return encodeSpecialChar(sString, sChar.charAt(0));
}

public static String decodeSpecialChar(String sString, String sChar) {
return decodeSpecialChar(sString, sChar.charAt(0));
}

/**
* 解析通过encodeSpecialChar方法编码过的特殊字符
*
* @param sString 源字符串
* @param sChar 特殊字符
* @return
*/
public static String decodeSpecialChar(String sString, char sChar) {
int iCode = sChar;
String sResult = sString;
sResult = StringUtils.replace(sResult, “$” + iCode + “$”, “” + sChar);
return sResult;
}

/**
* //替代非法XML字符
*/
public static String encodeXml(String sXml) {
sXml = encodeSpecialChar(sXml, ‘&’);
sXml = encodeSpecialChar(sXml, ‘>’);
sXml = encodeSpecialChar(sXml, ‘<‘);
return sXml;
}

/**
* //转回原串
*/
public static String decodeXml(String sXml) {
sXml = decodeSpecialChar(sXml, ‘<‘);
sXml = decodeSpecialChar(sXml, ‘>’);
sXml = decodeSpecialChar(sXml, ‘&’);
return sXml;
}

/**
* 将制定的特殊符号编码
*
* @str �?要编码的字符�?
* @splitStr 逗号分隔特殊字符 “‘,%,&,*,/,\”
*/
public static String encodeChars(String str, String splitStr) {
String[] splitArray = splitStr.split(“,”);
for (int i = 0; i < splitArray.length; i++) {
String specialChar = splitArray[i];
str = encodeSpecialChar(str, specialChar);
}
return str;
}

/**
* 将制定的特殊符号编码
*
* @str 逗号分隔特殊字符 “‘,%,&,*,/,\”
*/
public static String decodeChars(String str, String splitStr) {
String[] splitArray = splitStr.split(“,”);
for (int i = 0; i < splitArray.length; i++) {
String specialChar = splitArray[i];
str = decodeSpecialChar(str, specialChar);
}
return str;
}

public static String encodeChar(String str) {
str = encodeSpecialChar(str, ‘\”);
str = encodeSpecialChar(str, ‘;’);
str = encodeSpecialChar(str, ‘&’);
str = encodeSpecialChar(str, ‘”‘);
return str;
}

public static String decodeChar(String str) {
str = decodeSpecialChar(str, ‘\”);
str = decodeSpecialChar(str, ‘;’);
str = decodeSpecialChar(str, ‘&’);
str = decodeSpecialChar(str, ‘”‘);
return str;
}

/**
* 将Map中的值连成字符串
*
* @param map
* @param separator
* @return
*/
@SuppressWarnings(“unchecked”)
public static String serializeMapValue(Map map, String separator) {
String sResult = “”;
int i = 0;
for (Iterator iterator = map.values().iterator(); iterator.hasNext(); ) {
String sTmp = iterator.next().toString();
sResult += ((i == 0 ? “” : separator) + sTmp);
i++;
}
return sResult;
}

/**
* 把Clob转换为String
*
* @param clob 要转换的Clob对象
* @return 返回String类型
*/
public static String ClobToString(Clob clob) {
if (clob == null)
return “”;
String content = “”;

Reader instream;
try {
instream = clob.getCharacterStream();
char buffer[] = new char[500000];
instream.read(buffer);

content = new String(buffer).trim();

} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}

public static String stringTojeson(List<String> strList) {
String x = “”;
int i = 0;
for (String path : strList) {
x += (i++ > 0 ? “,” : “”) + “‘” + path + “‘”;
}
return x;
}

/**
* 不为�?
*
* @param str
* @return boolean
* @author
* @date 2009-5-4
* @remark
*/
public static boolean isNotEmpty(String str) {
return str != null && str.length() > 0;
}

/**
* 为空
*
* @param str
* @return boolean
* @author
* @date 2009-5-4
* @remark
*/
public static boolean isEmpty(String str) {
return str == null || str.length() <= 0;
}

/**
* 去掉字符串最后面字符
*
* @param sourceString
* @param cutString
* @return String
* @author
* @date 2009-7-14
* @remark
*/
public static String delEndString(String sourceString, String cutString) {
String resultStr = null;
if (isNotEmpty(sourceString) && isNotEmpty(cutString)) {
if (sourceString.endsWith(cutString)) {
resultStr = sourceString.substring(0, sourceString.length() – cutString.length());
} else {
resultStr = sourceString;
}
}
return resultStr;
}

public static String delStartString(String sourceString, String cutString) {
String resultStr = null;
if (isNotEmpty(sourceString) && isNotEmpty(cutString)) {
if (sourceString.startsWith(cutString)) {
resultStr = sourceString.substring(cutString.length(), sourceString.length());
} else {
resultStr = sourceString;
}
}
return resultStr;
}

/**
* 将用逗号分隔的ids 1,2 转换成in括号内用的格�? ‘1’,’2′
*
* @param ids
* @return String
* @author
* @date 2009-7-29
* @remark
*/
public static String idsToWhereIn(String ids) {

StringBuffer sb = new StringBuffer();
if (StringUtil.isNotEmpty(ids)) {
String[] arrId = ids.split(“,”);
for (String strId : arrId) {
sb.append(“‘” + strId + “‘,”);
}
}
if (sb.toString().length() > 0 && sb.toString().endsWith(“,”)) {
ids = StringUtil.delEndString(sb.toString(), “,”);
}
return ids;
}

/**
* 比较两个IP地址
*
* @param ip1
* @param ip2
* @return ip1>ip2 1
* ip1<ip2 -1
* ip1=ip2 0
*/
public static int compareIp(String ip1, String ip2) {
String tip1[] = StringUtil.split(ip1, “.”);
String tip2[] = StringUtil.split(ip2, “.”);
int result = 0;
for (int i = 0; i < tip1.length; i++) {
int n1 = Integer.parseInt(tip1[i]);
int n2 = Integer.parseInt(tip2[i]);
if (n1 < n2) {
result = -1;
break;
}
if (n1 > n2) {
result = 1;
break;
}
if (n1 == n2) {
continue;
}
}
return result;
}

/**
* 判断IP地址ipX是否在ip1 和ip2的范围之�?
*
* @param ip1
* @param ip2
* @param ipX
* @return
*/
public static boolean isIpBetween(String ip1, String ip2, String ipX) {
int r1 = compareIp(ipX, ip1);
if (r1 == 0)
return true;

int r2 = compareIp(ipX, ip2);
if (r2 == 0)
return true;

if (r1 == 1 && r2 == -1)
return true;

if (r1 == -1 && r2 == 1)
return true;

return false;

}

/**
* 计算规则字符串的�?
* 使用eviMap中存在的占位符的值替换指定字符串表达式中的占位符并返回替换后的字符串
* <p/>
* String exp = “/userfiles/image/${date(yyyyMM)}/${date(dd)}/${filename}”;
* Map ev = new HashMap();
* ev.put(“date”, new Date());
* ev.put(“filename”, 1234);
* String ret = StringUtil.evalExp(exp,ev);
* System.out.println(ret);
* 输出结果�?/userfiles/image/201003/18/1234
*
* @param exp
* @param eviMap
* @return
*/
public static String evalExp(String exp, Map eviMap) {
// 匹配�?有的dv规则的正则表达式
String patt = “\\$\\{[^}]+\\}”;
Pattern p3 = Pattern.compile(patt);
Matcher m3 = p3.matcher(exp);
while (m3.find()) {
String rule = m3.group();
Pattern pattern = Pattern.compile(“[\\{ \\( \\) \\}]+”);
String[] strs = pattern.split(rule);
String var = strs[1];//变量名称
Object val = eviMap.get(var);
String value = “”;
if (val != null) {
if (val instanceof Date) {
String fm = (strs.length >= 3 ? strs[2] : “yyyyMMdd”);
value = DateUtils.formatDate((Date) val, fm);
} else {
value = val.toString();
}
}
exp = StringUtil.replace(exp, rule, value);
}
return exp;
}

public static String getPinYin(String src) {
char t1[] = (char[]) null;
t1 = src.toCharArray();
String t2[] = new String[t1.length];
HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
t3.setVCharType(HanyuPinyinVCharType.WITH_V);
String t4 = “”;
int t0 = t1.length;
try {
for (int i = 0; i < t0; i++)
if (Character.toString(t1[i]).matches(“[\\u4E00-\\u9FA5]+”)) {
t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
t4 = (new StringBuilder(String.valueOf(t4))).append(t2[0]).toString();
} else {
t4 = (new StringBuilder(String.valueOf(t4))).append(Character.toString(t1[i])).toString();
}

} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
return t4;
}

//去除字符中重复出现的字符串
public static String rmRepeated(String src,String separator) {
String[] oldSrcList=src.split(separator);
StringBuffer newStr=new StringBuffer();
for(String s:oldSrcList){
if(newStr.toString().indexOf(s)<0){
newStr.append(s+separator);
}
}
return newStr.toString();
}
}

FileUploadUtil工具类

FileUploadUtil工具类


package beckey.util;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;

/**
*
*/
public class FileUploadUtil {
private static Logger logger=Logger.getLogger(FileUploadUtil.class);
private static String uploadDic;
static{
uploadDic="/WEB_INF/upload/";
File file=new File(uploadDic);
if(!file.exists()){
file.mkdirs();
}
}
private HttpServletRequest request;
public FileUploadUtil(HttpServletRequest request){
this.request=request;
}

/**
* 上传文件
* @return 成功数量
*/
public List<Map> upload(){
List mfiles=getUploadFile(this.request);
if(mfiles==null||mfiles.size()==0)return null;
List<Map> filePaths=new ArrayList<Map>();
for(MultipartFile mfile:mfiles){
String name=mfile.getOriginalFilename();
File file=new File(uploadDic+name);
try{
mfile.transferTo(file);
String charset=getFileCharset(file);
Map map=new HashMap(2);
map.put("path",uploadDic+name);
map.put("charset",charset);
filePaths.add(map);
logger.info("====成功上传文件:"+uploadDic+name);
}catch (IOException e){
logger.error("====文件上传失败:"+name,e);
}
}
return filePaths;
}

/**
* 线程上传
* @param multiFiles
*/
@Deprecated
public void upload(final MultipartFile[] multiFiles){
if(multiFiles==null && multiFiles.length==0) return;
for(int i=0;i<multiFiles.length;i++){
final MultipartFile multipartFile=multiFiles[i];
final String name=multipartFile.getOriginalFilename();
new Thread() {
@Override
public void run() {
File file=new File(uploadDic+name);
try{
multipartFile.transferTo(file);
logger.info("====成功上传文件:"+uploadDic+name);
}catch (IOException e){
logger.error("====文件上传失败:"+name,e);
}
}
}.start();
}

}
/**
* 获取待上传的所有文件
* @param request HttpServletRequest
* @return
*/
public List getUploadFile(HttpServletRequest request){
//创建多部分解析器
CommonsMultipartResolver resolver=new CommonsMultipartResolver(request.getSession().getServletContext());
if(!resolver.isMultipart(request))//无上传文件
return null;

//转换为多部分Request
MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
Iterator fileNames=multiRequest.getFileNames();
// MultipartFile[] files=new MultipartFile[10];
List files=new ArrayList();
while(fileNames.hasNext()){
MultipartFile file=multiRequest.getFile(fileNames.next());
//文件为空或者文件名为空均视为无文件
if(file==null || "".equals(file.getOriginalFilename()) )
continue;
files.add(file);
}
return files;
}

/**
* 简单判断并获取文件编码
* windows默认编码为GBK;此处只判断是否为UTF-8的编码
* 其余格式均当GBK处理
* @param file
* @return
*/
public static String getFileCharset(File file){
InputStream is=null;
try {
is= new FileInputStream(file);
byte[] b = new byte[1024];
is.read(b);
if(isUTF8(b))return "utf-8";
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if(is!=null)
is.close();
}catch (Exception e) {
}
}
return "GBK";
}

public static boolean isUTF8(byte[] rawtext) {
int score = 0;
int i, rawtextlen = 0;
int goodbytes = 0, asciibytes = 0;
// Maybe also use UTF8 Byte Order Mark: EF BB BF
// Check to see if characters fit into acceptable ranges
rawtextlen = rawtext.length;
for (i = 0; i < rawtextlen; i++) {
if ((rawtext[i] & (byte) 0x7F) == rawtext[i]) {
// 最高位是0的ASCII字符
asciibytes++;
// Ignore ASCII, can throw off count
} else if (-64 <= rawtext[i] && rawtext[i] <= -33
//-0x40~-0x21
&& // Two bytes
i + 1 < rawtextlen && -128 <= rawtext[i + 1]
&& rawtext[i + 1] <= -65) {
goodbytes += 2;
i++;
} else if (-32 <= rawtext[i]
&& rawtext[i] <= -17
&& // Three bytes
i + 2 < rawtextlen && -128 <= rawtext[i + 1]
&& rawtext[i + 1] <= -65 && -128 <= rawtext[i + 2]
&& rawtext[i + 2] 98) {
return true;
} else if (score > 95 && goodbytes > 30) {
return true;
} else {
return false;
}
}
}

HttpClientUtil工具类

HttpClientUtil工具类


package beckey.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.Header;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
* Http post get请求
* @author sugh
* 基于apache apache http-client4.0
*/
public class HttpClientUtil {
private static Logger logger = Logger.getLogger("HttpClientUtil");
/**
* http get����
* @param url
* @return
* @throws IOException
* @throws UnsupportedOperationException
*/
public static InputStream get(String url, Map map) {
// ��ȡhttpClient����
CloseableHttpClient httpClient = HttpClients.createDefault();
// ����response���󣬳�ʼ��response��ֵΪnull
CloseableHttpResponse response = null;
// ����StringBuffer�����������URL����
StringBuilder stringBuilder = new StringBuilder();
// �ж�urlֵ�Ƿ�Ϊnull�����urlֵΪ���ַ�����Ϊ���򷽷�ֱ�ӷ���һ��null
if (url == null || url.length() == 0) {
return null;
} else {
int index = url.indexOf("?");
// 如果index !=-1表示ip地址含有参数 -----http://210.44.76.138?k1=v1&k2=v2
// 此if else语句用以过滤掉 url后面的参数,使该ip变成 http://210.44.76.138这种没参数的形式
if (index != -1) {
// 获取不含?的Ip格式.
url = url.substring(0, index);
stringBuilder.append(url);
} else {
// 如果index==-1,表示该ip没有?,也就是没有参数,将原Ip加入stringBuilder对象-------http://210.44.76.138
// or http://210.44.76.138/
stringBuilder.append(url);
logger.info("index==-1 stringBuild" + stringBuilder.toString());
}
// 判断map受否为空,不为空则要拼装ip后面的参数
if (map != null && map.size() != 0) {
Set<Map.Entry> set = map.entrySet();
// 设置计数器,用于控制map.size=1和map.size>1时的执行
int count = 1;
for (Entry entry : set) {
String key = entry.getKey();
String value = entry.getValue();
if (count == 1) {
stringBuilder.append("?").append(key).append("=").append(value);
} else {
stringBuilder.append("&").append(key).append("=").append(value);
}
count++;
}
logger.info("url添加自定义参数之前的值:" + url);
logger.info("stringBuilder的值:" + stringBuilder.toString());
// 将参数添加到url中,形成新的带参数的URL格式
url = stringBuilder.toString();
}
}
// ����httpGet����
logger.info("url添加制定意之前的值:" + url);
RequestConfig defaultRequestConfig = RequestConfig.custom().setExpectContinueEnabled(true)
.setStaleConnectionCheckEnabled(true)
.setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setSocketTimeout(5000)
.setConnectTimeout(3000).setConnectionRequestTimeout(3000).build();
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);
try {
response = httpClient.execute(httpGet);
return dealResponse(response);
} catch (IOException e) {
// TODO Auto-generated catch block
// ����Ϊnull
return dealResponse(response);
// e.printStackTrace();
}
}

/**
* http post����
* @param url
* @param map
* @return InputStream (post请求的 内容)
*/
public static InputStream post(String url, Map map) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse httpresponse =null;
List params = new ArrayList();
InputStream is = null;
String body = null;
try {
// 设置客户端编码
RequestConfig defaultRequestConfig = RequestConfig.custom().setExpectContinueEnabled(true)
.setStaleConnectionCheckEnabled(true)
.setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setSocketTimeout(5000)
.setConnectTimeout(3000).setConnectionRequestTimeout(3000).build();
// Post请求
HttpPost httppost = new HttpPost(url);
// 设置post编码
httppost.setConfig(requestConfig);
if (map != null && map.size() != 0) {
Set<Map.Entry> set = map.entrySet();
// 设置计数器,用于控制map.size=1和map.size>1时的执行
for (Entry entry : set) {
String key = entry.getKey();
String value = entry.getValue();
params.add(new BasicNameValuePair(key, value));
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
String httppostContet=convertStreamToString(httppost.getEntity().getContent());
logger.info("url添加自定义参数之前的值:" + url);
logger.info("httppostContent的内容为:"+httppostContet);
// 将参数添加到url中,形成新的带参数的URL格式
}
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
// 设置报文头
httppost.setHeader("Content-Type", "text/xml;charset=UTF-8");
// 发送请求
httpresponse = httpClient.execute(httppost);
// 获取返回数据
return dealResponse(httpresponse);
} catch (Exception e) {
return dealResponse(httpresponse);
}

}
/**
* 根据要访问的url和传递的参数map值,访问get请求,并且根据 get请求返回的值 按照你制定的encode值格式化响应的内容
* @param url 要传递的url
* @param Map 请求时要传递的参数
* @param encode 对响应返回值做的编码格式转化,按照你制定的encode值格式化响应的内容
* @return String (响应response 的内容,内容格式自定义)
*/
public static String getString(String url, Map map, String encode) {
InputStream is = get(url, map);
if (is != null) {
try {
return stream2String(is, encode);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // TODO ��OSת��String
}
return null;
}
/**
* @param url 要传递的url
* @param Map 请求时要传递的参数
* @return String (响应response 的内容,response内容格式默认设置为utf-8)
*/
public static String getString(String url, Map map) {
return getString(url, map, "utf-8");
}
/**
* 处理response的内容, response.getContent
* @param response 要处理的response对象
* @return InputStream对象 --其中InputStream对象为reponse的content内容
* @throws IOException
* @throws UnsupportedOperationException
*/
public static InputStream dealResponse(HttpResponse response) {
InputStream is = null;
if (null == response) {
byte[] bt = new byte[4];
is = new ByteArrayInputStream(bt);
} else {
HttpEntity he = response.getEntity();
try {
if (response.getStatusLine().getStatusCode() == 200) {
is = he.getContent();
} else {
is = he.getContent();
}
} catch (UnsupportedOperationException | IOException e) {
e.printStackTrace();
}
}
return is;
}
/**
* InputStream对象按照指定的格式转化为字符串
* @param is
* @param encode
* @return convertContent2String (InputStream转化后的String内容)
* @throws UnsupportedEncodingException
*/
public static String stream2String(InputStream is, String encode) throws UnsupportedEncodingException {
String convertContent2String = convertStreamToString(is);
ChangeCharsetUtil changeCharsetUtil = new ChangeCharsetUtil();
if (changeCharsetUtil.GBK.equalsIgnoreCase(encode)) {
convertContent2String = changeCharsetUtil.toGBK(convertContent2String);
} else if (changeCharsetUtil.ISO_8859_1.equalsIgnoreCase(encode)) {
convertContent2String = changeCharsetUtil.toISO_8859_1(convertContent2String);
} else if (changeCharsetUtil.US_ASCII.equalsIgnoreCase(encode)) {
convertContent2String = changeCharsetUtil.toASCII(convertContent2String);
} else if (changeCharsetUtil.UTF_16.equalsIgnoreCase(encode)) {
convertContent2String = changeCharsetUtil.toUTF_16(convertContent2String);
} else if (changeCharsetUtil.UTF_16BE.equalsIgnoreCase(encode)) {
convertContent2String = changeCharsetUtil.toUTF_16BE(convertContent2String);
} else if (changeCharsetUtil.UTF_16LE.equalsIgnoreCase(encode)) {
convertContent2String = changeCharsetUtil.toUTF_16LE(convertContent2String);
} else if (changeCharsetUtil.UTF_8.equalsIgnoreCase(encode)) {
convertContent2String = changeCharsetUtil.toUTF_8(convertContent2String);
} else {
convertContent2String = convertContent2String;
}
return convertContent2String;
}
/**
* 解析出InputStream对象中的内容,并将其转化为字符串格式,没有对字符串进行格式转化处理,只是单纯的格式转化
* @param is 要转化为字符串的InputStream对象
* @return String (InputStream转化后的字符串)
* */
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String ip = "http://210.44.176.116/cjcx/zcjcx_list.php";
Map map = new HashMap();
map.put("post_xuehao", "12110404003");
// map.put("age", "10");
// map.put("11", "1dad0");
// map.put("ssd", "1gggggg0");
// map.put("ff", "10");
// map.put("k", null);
InputStream is=post("http://210.44.176.116/cjcx/zcjcx_login.html", map);
String content=getString(ip, null);
//String contentPost=convertStreamToString(is);
//String content = getString(ip, null);
System.out.println("content:" + content);
}

}

跳至工具栏