自动化脚本在eclipse中执行,没有问题。jenkins构建打包自动化脚本,在执行脚本时,遇到了脚本中发送的请求的参数为乱码,实现了如下一些解决办法:
1、设置操作系统环境JAVA_TOOL_OPTIONS = -Dfile.encoding=UTF-8
2、jenkins 系统管理> 系统设置 设置全局变量
3、修改代码,代码中把请求参数在使用前变成uft8 格式。响应输出流也专换成utf-8
para = new String(para.toString().getBytes(), "utf-8"); 使用参数
in = new BufferedReader( new InputStreamReader(conn.getInputStream(),"utf-8")); 响应输出流也专换成utf-8
public static String sendPost(String url, String param,String wexinsession) {
para = new String(para.toString().getBytes(), "utf-8");
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性 addRequestHeader("Content-Type","text/html;charset=UTF-8");
conn.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
conn.setRequestProperty("Host", PropsUtil.readValue("emdsServerHost"));
conn.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.setRequestProperty("Accept-Language", "zh-cn");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Origin", "http://xxx.xxx.xxx);
conn.setRequestProperty("Content-Length", "700");
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13C75 MicroMessenger/6.3.9 NetType/WIFI Language/zh_CN");
conn.setRequestProperty("Referer", "http://xxx.xxx.xxx/sss.ss"); conn.setRequestProperty("Cookie", wexinsession);
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader( new InputStreamReader(conn.getInputStream(),"utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
} // System.out.println(result);
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}