HttpClient的作用强大,真的是十分强大.

本实例是基于v4.3.3写的,,作用是模拟登陆后进行上下班打卡,,,使用htmlparser进行解析返回的html文件

关于HttpClient的一些详细介绍可以参考: HttpClient详解


Maven的主要配置

 <properties>
<jdk.version>1.6</jdk.version>
</properties> <dependencies>
<dependency>
<groupId>org.htmlparser</groupId>
<artifactId>htmlparser</artifactId>
<version>1.6</version>
</dependency> <!-- httpcomponents -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.3</version>
</dependency>
</dependencies>
<build>
<finalName>ROOT</finalName>
<plugins>
<!-- compiler插件, 设定JDK版本 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
<showWarnings>true</showWarnings>
<encoding>UTF-8</encoding>
<compilerArguments>
<verbose />
<bootclasspath>${java.home}\lib\rt.jar</bootclasspath>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>cn.ffcs.eis.TestEis</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>

Maven配置

 package cn.ffcs.clent;

 import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set; import org.apache.http.Header;
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.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.CookieSpec;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.impl.cookie.BestMatchSpecFactory;
import org.apache.http.impl.cookie.BrowserCompatSpec;
import org.apache.http.impl.cookie.BrowserCompatSpecFactory;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.htmlparser.Parser; /**
* HttpClient使用4.3.3,Parser使用1.6
* @author zkongbai
*
*/
public class HttpUtils { public static final String UTF_8 = "UTF-8";
public static CookieStore COOKIE_STORE = new BasicCookieStore(); public static void setCOOKIE_STORE(CookieStore cOOKIE_STORE) {
COOKIE_STORE = cOOKIE_STORE;
} public static HttpPost postForm(String url,Map<String, String> params,Map<String, String> hearders){
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList <NameValuePair>();
if(params != null){
Set<String> keySet = params.keySet();
for(String key : keySet) {
nvps.add(new BasicNameValuePair(key, params.get(key)));
}
}
if(hearders != null){
Set<Map.Entry<String, String>> mapping = hearders.entrySet();
for(Map.Entry<String, String> entry : mapping){
httpPost.setHeader(entry.getKey(),entry.getValue());
}
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(nvps, UTF_8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return httpPost;
} /**
* 使用默认的HttpClient发送Get请求
* @param url
* @return
*/
public static String get(String url) throws Exception{
HttpClient httpclient = HttpClients.createDefault();
String body = null;
HttpGet get = new HttpGet(url);
body = invoke(httpclient, get);
return body;
} /**
* 使用自定义HttpClient发送Get请求
* @param client
* @param url
* @return
*/
public static String get(HttpClient client,String url) throws Exception{
String body = null;
HttpGet get = new HttpGet(url);
body = invoke(client, get);
return body;
} /**
* 使用自定义HttpClient发送Get请求,并返回HttpResponse
* @param client
* @param url
* @return
*/
public static HttpResponse getAndResponse(HttpClient client,String url) throws Exception{
return sendRequest(client, new HttpGet(url));
} private static String invoke(HttpClient httpclient, HttpUriRequest httpost) throws Exception{
HttpResponse response = sendRequest(httpclient, httpost);
String body = paseResponse(response);
return body;
} public static HttpResponse sendRequest(HttpClient httpclient,HttpUriRequest httpost) throws Exception{
HttpResponse response = null;
try {
response = httpclient.execute(httpost);
} catch (ClientProtocolException e) {
throw e;
} catch (IOException e) {
throw e;
}
return response;
} public static String paseResponse(HttpResponse response) throws Exception{
//listHearders(response);
HttpEntity entity = response.getEntity();
// ContentType contentType = ContentType.getOrDefault(entity);
// System.out.println(contentType.toString());
String body = null;
try {
body = EntityUtils.toString(entity);
} catch (ParseException e) {
throw e;
} catch (IOException e) {
throw e;
} finally{
// if(response != null){
// if(response instanceof CloseableHttpResponse){
// try {
// ((CloseableHttpResponse) response).close();
// response = null;
// } catch (IOException e) {}
// }
// }
if(response != null){
try {
EntityUtils.consume(entity);
} catch (IOException e) {}
}
}
return body;
} /**
* Write htmL to file.
* 将请求结果以二进制形式放到文件系统中保存为.html文件,便于使用浏览器在本地打开 查看结果
*
* @param entity the entity
* @param pathName the path name
* @return HttpEntity.getContentLength() != -1 时,返回true
* @throws Exception the exception
*/
public static boolean writeHTMLtoFile(HttpEntity entity, String pathName) throws Exception{
int length = (int) entity.getContentLength();
byte[] bytes = null;
boolean flag = true;
if(length != -1){
bytes = EntityUtils.toByteArray(entity);
flag = false;
}else{
try {
bytes = "has nothing to write!".getBytes(UTF_8);
} catch (UnsupportedEncodingException e) {throw e;}
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(pathName);
fos.write(bytes);
fos.flush();
} catch (IOException e) {
throw e;
} finally{
if(fos != null){
try {
fos.close();
fos = null;
} catch (Exception e) {}
}
}
return flag;
} /**
* 将请求结果以二进制形式放到文件系统中保存为.html文件,便于使用浏览器在本地打开 查看结果
* @param entity
* @param pathName
* @return
* @throws Exception
*/
public static boolean writeString2File(String body, String pathName) throws Exception{
boolean flag = false;
FileOutputStream fos = null;
try {
byte[] bytes = body.getBytes(UTF_8);
fos = new FileOutputStream(pathName);
fos.write(bytes);
fos.flush();
flag = true;
} catch (IOException e) {
throw e;
} finally{
if(fos != null){
try {
fos.close();
fos = null;
} catch (Exception e) {}
}
}
return flag;
} /**
* 解析HttpResponse,并设置Cookie
* @param response
*/
@Deprecated
public static void setCookie(HttpResponse response){
String setCookie = nvl(response.getFirstHeader("Set-Cookie").getValue()).trim();
String JSESSIONID = setCookie.substring("JSESSIONID=".length(),setCookie.indexOf(";"));
System.out.println("JSESSIONID:" + JSESSIONID);
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID",JSESSIONID);
cookie.setVersion(0);
cookie.setDomain("127.0.0.1");
cookie.setPath("/CwlProClient");
//cookieStore.addCookie(cookie);
} /**
* 下次请求时候含有Cookie
* @param response
* @return
*/
public static CloseableHttpClient getHttpClientWithCookie() { CookieSpecProvider easySpecProvider = new CookieSpecProvider() {
public CookieSpec create(HttpContext context) {
return new BrowserCompatSpec() {
@Override
public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {
COOKIE_STORE.addCookie(cookie);
}
};
}
};
Registry<CookieSpecProvider> r = RegistryBuilder
.<CookieSpecProvider> create()
.register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
.register(CookieSpecs.BROWSER_COMPATIBILITY,new BrowserCompatSpecFactory())
.register("easy", easySpecProvider)
.build(); RequestConfig requestConfig = RequestConfig
.custom()
.setCookieSpec("easy")
.setSocketTimeout(10000)
.setConnectTimeout(10000)
.build(); CloseableHttpClient httpclient = HttpClients
.custom()
.setDefaultCookieSpecRegistry(r)
.setDefaultRequestConfig(requestConfig)
.setDefaultCookieStore(COOKIE_STORE)
.build();
return httpclient;
}
public static CloseableHttpClient getHttpClientWithCookie2(){
return HttpClients
.custom()
.setDefaultCookieStore(COOKIE_STORE)
.build();
} /**
* 遍历所有的Cookie
*/
public static void listCookie(){
List<Cookie> cookies = HttpUtils.COOKIE_STORE.getCookies();
if(cookies != null && !cookies.isEmpty())
for(Cookie c : cookies){
System.out.println("用户Cookie....\t"+c);
}
else
System.err.println("暂时无Cookie");
} /**
* 遍历所有的请求头信息
* @param response
*/
public static void listHearders(HttpResponse response){
//请求头信息
Header[] heards = response.getAllHeaders();
for (Header s : heards) {
System.out.println("用户 header:\t" + s);
}
}
/**
* 通过string的HTML,解析HTML
* @param body
*/
public static Parser parseHTML(String body){
Parser parser = Parser.createParser(body,UTF_8);
return parser;
} /**
* 解析HTML
* @param url
* @return
* @throws Exception
*/
public static Parser parseHTMLByURL(String url) throws Exception{
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
conn.setRequestProperty("Accept-Charset", "UTF-8");
Parser parser = new Parser(conn);
return parser;
} /**
* 空值处理,转换为默认值
* @param v 输入值
* @param defaultValue 默认值
* @return 非 null值
*/
public static String nvl(String v,String defaultValue){
return v==null?defaultValue==null?"":defaultValue:v;
}
/**
* 空值处理,转换为默认值
* @param v 输入值
* @return 非 null值
*/
public static String nvl(String v){
return nvl(v,null);
}
}

HttpClient4.3.3写法

 package cn.ffcs.eis;

 import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Random; import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.OrFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.InputTag;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableHeader;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.SimpleNodeIterator; import cn.ffcs.clent.HttpUtils;
import cn.ffcs.eis.constant.EisInfo;
import cn.ffcs.eis.constant.EisURL;
import cn.ffcs.eis.pojo.EisAccount;
import cn.ffcs.eis.utils.EisDateUtils; public class EisWorker { public EisWorker(){ } private static Map<String,String> login_param = new HashMap<String,String>();
private static Map<String,String> head_param = new HashMap<String,String>();
private static Map<String,String> userInfo_param = new HashMap<String,String>(); public static Map<String, String> getLogin_param() {
return login_param;
}
public static Map<String, String> getHead_param() {
return head_param;
}
public static Map<String, String> getUserInfo_param() {
return userInfo_param;
} /**
* 下班打卡需要的打卡小时数
*/
private static final String WORK_HOUR = "9"; static {
login_param.put("login_submit", "on");
login_param.put("login_do_redirect", "1");
login_param.put("no_cert_storing", "on");
login_param.put("j_authscheme", "default"); head_param.put("Accept", "application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
head_param.put("Accept-Encoding", "gzip, deflate");
head_param.put("Accept-Language", "zh-CN");
head_param.put("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; InfoPath.2; .NET4.0C; .NET4.0E)");
head_param.put("Referer", EisURL.URL_LOGIN);
head_param.put("Content-Type", "application/x-www-form-urlencoded"); //userInfo_param.put("btnsave","%E4%BF%9D%E5%AD%98");
} /**
* 登录,返回带Cookie的HttpClient
* @param userName
* @param password
* @return
* @throws Exception
*/
public static HttpClient login(EisAccount account) throws Exception{
HttpUtils.setCOOKIE_STORE(new BasicCookieStore());
String userName = account.getUserName().trim();
String password = account.getPasswd().trim(); login_param.put("j_user", userName);
login_param.put("j_password", password);
HttpPost post = HttpUtils.postForm(EisURL.URL_LOGIN, login_param,head_param);
HttpClient httpclient = HttpUtils.getHttpClientWithCookie();
HttpResponse response = httpclient.execute(post); //含有下次请求的Cookie: MYSAPSSO2
//HttpUtils.listHearders(response);
login_param.remove("j_user");
login_param.remove("j_password");
HttpEntity entity = response.getEntity();
// HttpUtils.writeHTMLtoFile(entity,getSuffixName("login",userName));
EntityUtils.consume(entity);
response = HttpUtils.getAndResponse(httpclient, EisURL.URL_JSESSION);
_setJSESSION(response);
System.out.println("===============login====分割线==================================");
return _getLtpaToken(httpclient);
} private static HttpClient _getLtpaToken(HttpClient clientWithCookie) throws Exception{
head_param.put("Referer","http://bem.ffcs.cn:81/mis/EISTask.aspx");
HttpUtils.get(clientWithCookie, EisURL.URL_LtpaToken);//使得下次请求含有LtpaToken
return HttpUtils.getHttpClientWithCookie();
} /**
* 获取打卡相关信息,登录后需要调用
* @param clientWithCookie
* @throws Exception
*/
public static HttpClient userWorkInfo(HttpClient clientWithCookie,String loginName) throws Exception{
head_param.put("Referer","http://bem.ffcs.cn:81/mis/EISIndex.aspx");
HttpPost post = HttpUtils.postForm(EisURL.URL_USERWORK_INFO,null,head_param);
HttpResponse response = clientWithCookie.execute(post);
//HttpUtils.listHearders(response);
_setAspNetSession(response); //注入含ASP.NET_SessionId的Cookie
HttpEntity entity = response.getEntity();
// HttpUtils.writeHTMLtoFile(entity, "C:/userWorkInfo.html");
String result = EntityUtils.toString(entity);
if("请登录".equals(result)){
HttpUtils.writeString2File(result, getSuffixName("error", loginName));
throw new Exception(loginName+"登录失败");
}
else
System.out.println("---------------->"+loginName+"登录成功");
EntityUtils.consume(entity);
parseUserInfo(result);
System.out.println("===============userWorkInfo====分割线==================================");
return HttpUtils.getHttpClientWithCookie();
} /**
* 上班打卡
* @param clientWithCookie
* @throws Exception
*/
public static String submitOnWork(HttpClient clientWithCookie) throws Exception{
userInfo_param.remove("ibOn");
head_param.put("Referer","http://bem.ffcs.cn:81/hrs/work/UserWork.aspx");
HttpPost post = HttpUtils.postForm(EisURL.URL_USERWORK_INFO, userInfo_param,head_param);
HttpResponse response = clientWithCookie.execute(post);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
//HttpUtils.listCookie();
EntityUtils.consume(entity);
System.out.println("===============上班打卡====分割线==================================");
return result;
} /**
* 下班打卡
* @param clientWithCookie
* @return
* @throws Exception
*/
@SuppressWarnings("unused")
public static String submitOffWork(HttpClient clientWithCookie,String loginName) throws Exception{
executeBeforeWorkOff(clientWithCookie,loginName);
head_param.put("Referer",EisURL.URL_USERWORK_OFF+"?userno="+userInfo_param.get("userno")+"work=1");
head_param.put("Accept", "text/html, application/xhtml+xml, */*");
head_param.put("Host", "bem.ffcs.cn:81");
head_param.put("Connection", "Keep-Alive");
head_param.put("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
// userInfo_param.put("flag", "1");//非正常时间打卡下班
// userInfo_param.put("date", EisDateUtils.getCurDateFormatStr());//获取当前日期 Map<String, String> submitParam = new HashMap<String,String>();
String reqUri = "?";
for(Map.Entry<String, String> entry : userInfo_param.entrySet()){
if(!entry.getKey().startsWith("pc") && !entry.getKey().startsWith("ibOn")){
submitParam.put(entry.getKey(),entry.getValue());
if(!"__VIEWSTATE".equalsIgnoreCase(entry.getKey()))
reqUri += entry.getKey()+"="+entry.getValue()+"&";
}
}
HttpPost post = HttpUtils.postForm(EisURL.URL_USERWORK_OFF, submitParam,head_param);
HttpResponse response = HttpUtils.getHttpClientWithCookie2().execute(post);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
// String result = HttpUtils.get(HttpUtils.getHttpClientWithCookie2(), EisURL.URL_USERWORK_OFF+reqUri);//Get请求方式
System.out.println("===============下班打卡====分割线==================================");
return result;
} /**
* 检查上班打卡时间
* @param clientWithCookie
* @param no
* @param cnName
* @throws Exception
*/
public static void checkWork(HttpClient clientWithCookie,String loginName) throws Exception{
head_param.put("Referer","http://bem.ffcs.cn:81/hrs/work/UserWork.aspx");
login_param.put("strUserNo",userInfo_param.get("pcUserno"));
login_param.put("strUserName",userInfo_param.get("pcUsername"));
HttpPost post = HttpUtils.postForm(EisURL.URL_CHECK_WORK, login_param,head_param);
HttpResponse response = clientWithCookie.execute(post);
HttpEntity entity = response.getEntity();
HttpUtils.writeHTMLtoFile(entity, getSuffixName("checkWork", loginName));
EntityUtils.consume(entity);
} /**
* 下班时间检查
* @param clientWithCookie
* @param no
* @throws Exception
*/
public static void checkOffTime(HttpClient clientWithCookie,String loginName) throws Exception{
head_param.put("Referer","http://bem.ffcs.cn:81/hrs/work/UserWork.aspx");
login_param.put("strUserNo",userInfo_param.get("pcUserno"));
HttpPost post = HttpUtils.postForm(EisURL.URL_LOGIN, login_param,head_param);
HttpResponse response = clientWithCookie.execute(post);
HttpEntity entity = response.getEntity();
HttpUtils.writeHTMLtoFile(entity, getSuffixName("checkOffTime", loginName));
EntityUtils.consume(entity);
} /**
* 解析返回的打卡信息,并检查与重置ip,将有效信息存放内存中
* @param body
* @throws Exception
*/
private static void parseUserInfo(String body) throws Exception{
// String url = "http://zkongbai:8080/userWorkInfo.html";
// Parser parser = HttpUtils.parseHTMLByURL(url);
Parser parser = HttpUtils.parseHTML(body);
NodeFilter filter = new AndFilter(new HasAttributeFilter ("type","hidden"),new TagNameFilter ("input"));
NodeFilter filter2 = new AndFilter(new HasAttributeFilter ("type","image"),new TagNameFilter ("input"));
// NodeList nodeList = parser.parse(null);
NodeList nodeList = parser.extractAllNodesThatMatch(new OrFilter(filter, filter2));
SimpleNodeIterator it = nodeList.elements();
Node node = null;
InputTag tag = null;
while(it.hasMoreNodes()){
node = it.nextNode();
// System.out.println(node.toHtml());
tag = ((InputTag)node);
userInfo_param.put(tag.getAttribute("id"),nvl(tag.getAttribute("value")));
// System.out.println(tag.getAttribute("id")+"="+tag.getAttribute("value"));
}
if("0".equals(userInfo_param.get("pcPostrand"))){
if(userInfo_param.get("pcIpAddress") != null && !"".equals(userInfo_param.get("pcIpAddress"))){
userInfo_param.put("pcLocalIpAddress",userInfo_param.get("pcIpAddress"));
}else{
throw new Exception(userInfo_param.get("pcUsername")+",OA没有登记您的考勤IP,请联系信息中心。");
}
}
effectiveIBON();
}
private static void _setAspNetSession(HttpResponse response){
if(response.getFirstHeader("Set-Cookie")==null)
return;
String setCookie = nvl(response.getFirstHeader("Set-Cookie").getValue()).trim();
String aspSession = setCookie.substring("ASP.NET_SessionId=".length(),setCookie.indexOf(";"));
//System.out.println("ASP.NET_SessionId:" + aspSession);
BasicClientCookie cookie = new BasicClientCookie("ASP.NET_SessionId",aspSession);
cookie.setVersion(0);
cookie.setDomain("bem.ffcs.cn");
cookie.setPath("/");
HttpUtils.COOKIE_STORE.addCookie(cookie);
}
private static void _setJSESSION(HttpResponse response){
Header[] heards = response.getAllHeaders();
String setCookie = null;
for (Header heard : heards) {
if("Set-Cookie".equalsIgnoreCase(heard.getName())){
setCookie = heard.getValue();
if(setCookie.contains("JSESSIONID=")){
String JSESSIONID = setCookie.substring("JSESSIONID=".length(),setCookie.indexOf(";"));
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID",JSESSIONID);
cookie.setVersion(0);
cookie.setDomain(".ffcs.cn");
cookie.setPath("/");
HttpUtils.COOKIE_STORE.addCookie(cookie);
}else if(setCookie.contains("sapj2ee_*=")){
String JSESSIONID = setCookie.substring("sapj2ee_*=".length(),setCookie.indexOf(";"));
BasicClientCookie cookie = new BasicClientCookie("sapj2ee_*",JSESSIONID);
cookie.setVersion(0);
cookie.setDomain("eis.ffcs.cn");
cookie.setPath("/");
HttpUtils.COOKIE_STORE.addCookie(cookie);
}
}
}
} /**
* 解析上班打卡结果,判断是否成功打卡
* @param clientWithCookie
* @param othURI
* @param logName
* @throws Exception
*/
public static void parseSubmitOnWorkResult(HttpClient clientWithCookie,String othURI,String logName) throws Exception{
//String othURI = "hrs/work/UserWorkList.aspx?id=12687061&flag=1#";
othURI = java.net.URLDecoder.decode(othURI,HttpUtils.UTF_8);
String result = HttpUtils.get(clientWithCookie, EisURL.DOMAIN+othURI);
HttpUtils.writeString2File(result,getSuffixName("上班打卡结果",logName));
Parser parser = HttpUtils.parseHTML(result);
NodeFilter filter = new NodeClassFilter(TableTag.class);
NodeList nodeList = parser.extractAllNodesThatMatch(filter);
for (int i = 0; i < nodeList.size(); ++i) {
if (nodeList.elementAt(i) instanceof TableTag) {
TableTag tag = (TableTag) nodeList.elementAt(i);
TableRow[] rows = tag.getRows();
for (int j = 0; j < rows.length; ++j) {
TableRow row = (TableRow) rows[j];
// the reason to get headers is to parse <th> tag
TableHeader[] headers = row.getHeaders();
for (int k = 0; k < headers.length; ++k) {//标签头
// System.out.print("tag标签为:" + headers[k].getTagName().replaceAll("\\s", "")+"\t");
// System.out.print("标签的内容为:"+ headers[k].getStringText().replaceAll("\\s", "")+"\t");
}
TableColumn[] columns = row.getColumns();
for (int k = 0; k < columns.length; ++k) {//标签体
String info = columns[k].toPlainTextString().replaceAll("\\s", "");
if("tdAmRemark".equalsIgnoreCase(columns[k].getAttribute("id"))){
System.out.println("打卡结果:"+info);
if(!"正常".equals(info)){
System.err.println(logName+EisDateUtils.getCurDateFormatStr()+"上班打卡失败");
throw new Exception(logName+EisDateUtils.getCurDateFormatStr()+"上班打卡失败");
}
}
}
//System.out.println();
}
}
}
} /**
* 解析上班打卡信息,据分析,body的信息只能含有一个超链接
* @param body
*/
public static void parseSubmitOnWork(HttpClient clientWithCookie,String body,String logName) throws Exception{
Parser parser = HttpUtils.parseHTML(body);
NodeFilter filter = new TagNameFilter ("a");
NodeList nodeList = parser.extractAllNodesThatMatch(filter);
SimpleNodeIterator it = nodeList.elements();
Node node = null;
LinkTag tag = null;
boolean success = false;
String othURI = null;
int falg = 0;
while(it.hasMoreNodes()){
++falg;
node = it.nextNode();
// System.out.println(node.toHtml());
tag = ((LinkTag)node);
othURI = tag.getAttribute("href");
if(othURI != null && othURI.contains("UserWorkList.aspx")){
System.out.println("打卡结果:href:"+EisURL.DOMAIN+othURI);
success = true;
}
}
if(!success || falg>1){
HttpUtils.writeString2File(body,getSuffixName("error", logName));
throw new Exception("解析上班打卡信息失败,请检查代码");
}
parseSubmitOnWorkResult(clientWithCookie,othURI,logName);
System.out.println("===============上班打卡结果====分割线==================================");
} /**
* 解析下班打卡信息
* @param clientWithCookie
* @param body
* @throws Exception
*/
public static void parseSubmitOffWork(HttpClient clientWithCookie,String body,String loginName) throws Exception{
HttpUtils.writeString2File(body, getSuffixName("下班班打卡结果", loginName));
System.out.println("===============下班打卡结果====分割线==================================");
} /**
* 下班打卡前,获取相关信息
* @param body
* @throws Exception
*/
private static void executeBeforeWorkOff(HttpClient clientWithCookie,String loginName) throws Exception{
userInfo_param.put("work", "1");
userInfo_param.put("userno",userInfo_param.get("pcUserno")); // head_param.put("Referer",EisURL.URL_USERWORK_OFF);
// HttpPost post = HttpUtils.postForm(EisURL.URL_USERWORK_OFF, userInfo_param,head_param);
// HttpResponse response = clientWithCookie.execute(post);
// HttpEntity entity = response.getEntity();
// String result = EntityUtils.toString(entity);
String result = HttpUtils.get(clientWithCookie, EisURL.URL_USERWORK_OFF+"?work=1&userno="+userInfo_param.get("userno")); Parser parser = HttpUtils.parseHTML(result); NodeFilter filter1 = new AndFilter(new HasAttributeFilter ("id","rownum"),new TagNameFilter ("input"));
NodeFilter filter2 = new AndFilter(new HasAttributeFilter ("class","cinput"),new TagNameFilter ("input"));
NodeFilter filter3 = new AndFilter(new HasAttributeFilter ("type","hidden"),new TagNameFilter ("input"));
NodeFilter filter = new OrFilter(new NodeFilter[]{filter1, filter2,filter3});
// NodeList nodeList = parser.parse(null);
NodeList nodeList = parser.extractAllNodesThatMatch(filter);
SimpleNodeIterator it = nodeList.elements();
Node node = null;
InputTag tag = null;
int hasXm = 0; //是否有可选的项目
while(it.hasMoreNodes()){
node = it.nextNode();
tag = (InputTag)node;
if("rownum".equalsIgnoreCase(tag.getAttribute("name"))){
if(nvl(tag.getAttribute("value")).length()==0){
userInfo_param.put(tag.getAttribute("id"),tag.getAttribute("value"));
HttpUtils.writeString2File(result, getSuffixName("error", loginName));
throw new Exception("解析失败");
}
}else if(tag.getAttribute("name").contains("sum-day-")){
userInfo_param.put(tag.getAttribute("id"),WORK_HOUR);
}else if(tag.getAttribute("name").contains("item-")){
userInfo_param.put(tag.getAttribute("name"),nvl(tag.getAttribute("value")));
}else if (tag.getAttribute("name").contains("input-")){
if(hasXm == 0)
userInfo_param.put(tag.getAttribute("name"),WORK_HOUR);//下班打卡的项目
else
userInfo_param.put(tag.getAttribute("name"),nvl(tag.getAttribute("value")));
hasXm++;
}else if(tag.getAttribute("name").equalsIgnoreCase("__VIEWSTATE")){
userInfo_param.put(tag.getAttribute("id"),nvl(tag.getAttribute("value")));
}
}
if(hasXm==0){
HttpUtils.writeString2File(result, getSuffixName("error", loginName));
throw new Exception("解析失败 或 暂无可打卡的项目,请查看代码 或 联系信息中心");
}
} /**
* 空值处理,转换为默认值
* @param v 输入值
* @param defaultValue 默认值
* @return 非 null值
*/
public static String nvl(String v,String defaultValue){
return v==null?defaultValue==null?"":defaultValue:v;
}
/**
* 空值处理,转换为默认值
* @param v 输入值
* @return 非 null值
*/
public static String nvl(String v){
return nvl(v,null);
} /**
* 上班图标的有效的位置
*/
private static void effectiveIBON(){
Random random = new Random();
userInfo_param.put("ibOn.x", String.valueOf(58+random.nextInt(6)%6-3));
userInfo_param.put("ibOn.y", String.valueOf(17+random.nextInt(4)%4-2));
}
/**
* 下班班图标的有效的位置
*/
@SuppressWarnings("unused")
private static void effectiveIBOFF(){
Random random = new Random();
userInfo_param.put("ibOff.x", String.valueOf(68+random.nextInt(6)%6-3));
userInfo_param.put("ibOff.y", String.valueOf(17+random.nextInt(4)%4-2));
} /**
* 根据用户名生成对应的文件后缀名html
* @param fileName 文件名称.不含路径
* @param userName 用户
* @return
*/
public static String getSuffixName(String fileName,String userName,String...strings){
if(userName == null || userName.length()==0)
userName = "anonymous";
String path = EisInfo.LOG_PATH+userName+File.separator+EisDateUtils.getCurDateFormatStr();
File file = new File(path);
if(!file.exists()){
file.mkdirs();
}
if(strings != null && strings.length>0){
if("log".equals(strings[0]))
return path+File.separator+fileName+"."+userName+"."+EisDateUtils.getCurDateFormatStr()+".log";
}
return path+File.separator+fileName+"."+userName+"."+EisDateUtils.getCurDateFormatStr()+"."+Calendar.getInstance().getTimeInMillis()+".html";
}
}

EisWorker

 package cn.ffcs.eis.utils;

 import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date; public class EisDateUtils { public static final SimpleDateFormat fullDateFormat = new SimpleDateFormat("yyyy-MM-dd");
public static final SimpleDateFormat fullTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static String getCurDateFormatStr(){
Calendar c = Calendar.getInstance();
return fullDateFormat.format(c.getTime());
} public static String getCurTimeFormatStr(){
Calendar c = Calendar.getInstance();
return fullTimeFormat.format(c.getTime());
} public static String getDateFormatStr(Date date){
Calendar c = Calendar.getInstance();
c.setTime(date);
return fullDateFormat.format(c.getTime());
} /**
* 判断某个时间是否在某段区间内
* @param start
* @param end
* @param date 需要判断的时间,为空时,则为系统当前时间
* @return
*/
public static boolean isAtCertainTime(String start,String end,Date date,SimpleDateFormat format){
if(date == null){
date = Calendar.getInstance().getTime();
}
if(format == null){
format = fullTimeFormat;
}
Date StartDate = parseTime(start,format);
Date endDate = parseTime(end,format);
return date.getTime() >= StartDate.getTime() && date.getTime() <= endDate.getTime();
} /**
* 判断某个时间是否在某段区间内
* @param start
* @param end
* @param date 需要判断的时间,为空时,则为系统当前时间
* @return
*/
public static boolean isAtCertainTime(Date start,Date end,Date date){
if(date == null){
date = Calendar.getInstance().getTime();
}
return date.getTime() >= start.getTime() && date.getTime() <= end.getTime();
} /**
* @param date
* @param format
* @return
*/
public static Date parseDate(String date,SimpleDateFormat format){
if(format == null){
format = new SimpleDateFormat("yyyy-MM-dd");
}
try {
return format.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* @param date
* @param format
* @return
*/
public static Date parseTime(String date,SimpleDateFormat format){
if(format == null){
format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
try {
return format.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}

EisDateUtils

 package cn.ffcs.eis.pojo;

 public class EisAccount {

     private String userName;
private String passwd; public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
} public EisAccount(String userName, String passwd) {
this();
this.userName = userName;
this.passwd = passwd;
}
public EisAccount() {
}
public EisAccount(String userName) {
this(userName,"123456");
} @Override
public String toString() {
return "EisAccount [userName=" + userName + ", passwd=" + passwd + "]";
} }

EisAccount

 package cn.ffcs.eis.constant;

 import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle; import cn.ffcs.clent.HttpUtils;
import cn.ffcs.eis.pojo.EisAccount; public class EisInfo { /**
* 账号
*/
private static final List<EisAccount> accounts = new ArrayList<EisAccount>(); /**
* 日志路径
*/
public static final String LOG_PATH = HttpUtils.nvl(ResourceBundle.getBundle("account").getString("logPath")).trim(); public static List<EisAccount> getAccounts() {
return accounts;
} /**
*
*/
public static void setAccountFromProperties(){
String loginName = HttpUtils.nvl(ResourceBundle.getBundle("account").getString("loginName")).trim();
loginName = loginName.replaceFirst("loginName=", "");
String[] accounts = loginName.split(";");
for(String s : accounts){
if(s==null || s.length()==0)
continue;
if(s.indexOf("/")<0)
getAccounts().add(new EisAccount(s));
else
getAccounts().add(new EisAccount(s.split("/")[0],s.split("/")[1]));
} } static{
//初始化账号信息
// accounts.add(new EisAccount("luth"));
accounts.add(new EisAccount("dingyw"));
accounts.add(new EisAccount("zhaoshh"));
// accounts.add(new EisAccount("wangwm"));
accounts.add(new EisAccount("chenxinfei"));
setAccountFromProperties();
} }

EisInfo

 此处省略

EisURL

 package cn.ffcs.eis;

 import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Random; import org.apache.http.client.HttpClient; import cn.ffcs.eis.constant.EisInfo;
import cn.ffcs.eis.pojo.EisAccount;
import cn.ffcs.eis.utils.EisDateUtils; /**
* 先参考类 EisInfo,在Eclipse使用Package打包成jar,直接成可运行jar文件
* @author zkongbai
*
*/
public class TestEis { private static List<EisAccount> accounts = EisInfo.getAccounts(); /**
* 注意打卡时间
* @param args
*/
public static void main(String[] args) {
try {//重置输出流
System.setOut(new PrintStream(new FileOutputStream(new File(EisWorker.getSuffixName("anonymous","out","log")),true)));
System.setErr(new PrintStream(new FileOutputStream(new File(EisWorker.getSuffixName("anonymous","err","log")),true)));
} catch (Exception e2) {} Random random = new Random();
String zero = EisDateUtils.getCurDateFormatStr()+" 07:00:00";
String start = EisDateUtils.getCurDateFormatStr()+" 08:30:00";
String end = EisDateUtils.getCurDateFormatStr()+" 17:30:00";
String endDay = EisDateUtils.getCurDateFormatStr()+" 23:59:59"; String result = null;
String userName = null; if(!EisDateUtils.isAtCertainTime(start, end, null, null))//未在打卡时间内才允许打卡
for(EisAccount account : accounts){
try {
Thread.sleep(1000L*random.nextInt(5));//10s内的任意时间
} catch (Exception e1) {}
System.out.println(account);
userName = account.getUserName();
try {
HttpClient client = EisWorker.login(account);
client = EisWorker.userWorkInfo(client,userName);
//下班打卡
if(EisDateUtils.isAtCertainTime(end, endDay, null, null)){
result = EisWorker.submitOffWork(client,userName);
EisWorker.parseSubmitOffWork(client,result,userName);
}
//上班打卡
if(EisDateUtils.isAtCertainTime(zero, start, null, null)){
if("".equals(EisWorker.getUserInfo_param().get("ibOn"))){//未打卡
result = EisWorker.submitOnWork(client);
EisWorker.parseSubmitOnWork(client,result,userName);
}else
System.err.println(userName+" 已打卡");
} } catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
else System.out.println("当前时间:"+EisDateUtils.getCurTimeFormatStr()+" 未到正常打卡时间");
} }

顺带说句,,,使用maven可以直接打成jar包,,将所有外部依赖的jar都添加,的确很吊

在eclipse中,使用run as-> run configuration->package命令就可以,,打成的jar文件默认在target里面,使用java -jar ROOT.jar直接运行,方便吧.

做成一个bat脚本,放在开机关机程序里面,,碉堡了

还有一个配置文件,忘了说了account.properties,放在classpath路径下

 #1,the default password is 123456.if so ,then,you can ignore the password.
#2,you should have a Java SE Runtime Environment,and the version should higher than 1.7.0_60
#3,the Computer must access to http://eis.ffcs.cn/
#4,if the Operating System is linux/unix,you must modify the logPath.such as logPath=/eis/eisWork/
#eg: loginName=xshh;luth;...
#eg: loginName=xaoshh/123456;luth/123456
loginName=
logPath=c:/eis/eisWork/

HttpClient(4.3.3)实例讲解的更多相关文章

  1. float实例讲解

    float实例讲解 float是个强大的属性,在实际前端开发过程中,人们经常拿它来进行布局,但有时,使用的不好,也麻烦多多啊. 比如,现在我们要实现一个两列布局,左边的列,宽度固定:右边的列,宽度自动 ...

  2. S3C2440上RTC时钟驱动开发实例讲解(转载)

    嵌入式Linux之我行,主要讲述和总结了本人在学习嵌入式linux中的每个步骤.一为总结经验,二希望能给想入门嵌入式Linux的朋友提供方便.如有错误之处,谢请指正. 共享资源,欢迎转载:http:/ ...

  3. 实例讲解Oracle数据库设置默认表空间问题

    实例讲解Oracle数据库设置默认表空间问题   实例讲解Oracle数据库设置默认表空间问题,阅读实例讲解Oracle数据库设置默认表空间问题,DBA们经常会遇到一个这样令人头疼的问题:不知道谁在O ...

  4. 基于tcpdump实例讲解TCP/IP协议

    前言 虽然网络编程的socket大家很多都会操作,但是很多还是不熟悉socket编程中,底层TCP/IP协议的交互过程,本文会一个简单的客户端程序和服务端程序的交互过程,使用tcpdump抓包,实例讲 ...

  5. makefile基础实例讲解 分类: C/C++ 2015-03-16 10:11 66人阅读 评论(0) 收藏

    一.makefile简介 定义:makefile定义了软件开发过程中,项目工程编译链.接接的方法和规则. 产生:由IDE自动生成或者开发者手动书写. 作用:Unix(MAC OS.Solars)和Li ...

  6. 实例讲解Linux系统中硬链接与软链接的创建

    导读 Linux链接分两种,一种被称为硬链接(Hard Link),另一种被称为符号链接(Symbolic Link).默认情况下,ln命令产生硬链接.硬链接与软链接的区别从根本上要从Inode节点说 ...

  7. spring事务传播机制实例讲解

    http://kingj.iteye.com/blog/1680350   spring事务传播机制实例讲解 博客分类:   spring java历险     天温习spring的事务处理机制,总结 ...

  8. 实例讲解MySQL联合查询

    好了终于贴完了MySQL联合查询的内容了,加上上一篇一共2篇,都是我转载的,实例讲解MySQL联合查询.那下面就具体讲讲简单的JOIN的用法了.首先我们假设有2个表A和B,他们的表结构和字段分别为: ...

  9. Html代码seo优化最佳布局实例讲解

    搜索引擎对html代码是非常优化的,所以html的优化是做好推广的第一步.一个符合seo规则的代码大体如下界面所示. 1.<!–木庄网络博客–> 这个东西是些页面注释的,可以在这里加我的& ...

随机推荐

  1. 关于JQ的$.deferred函数。参考网络文档

    由于jQuery版本问题对Deferred对象的实现有所不同,具体请参照jQuery api:   jQuery.Deferred()基于Promises/A规范实现,因为jQuery本身的设计风格, ...

  2. TCP状态转移图学习总结

    http://blog.csdn.net/hairetz/article/details/6221620 这是网络编程的基础,tcp的状态转移图说到底就是一个状态机的不同状态之间的转换关系以及触发这些 ...

  3. js关于函数调用

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  4. C++string中有关大小和容量的函数浅析

    1.length()与size() length是因为沿用C语言的习惯而保留下来的,string类最初只有length,引入STL之后,为了兼容又加入了size,它是作为STL容器的属性存在的,便于符 ...

  5. 13.KVM安装之网桥

    安装必须的几个库和软件(最好下载一个163的yum源,速度快点) $ yum -y install kvm python-virtinst libvirt tunctl bridge-utils vi ...

  6. JPA入门案例详解(附源码)

    1.新建JavaEE Persistence项目

  7. max-width实现图片的自适应

    在自适应布局中,有时候会让图片随着宽度的变化相应的放大或者缩小,或者说让图片等比缩放,但是每个图片的大小又不一样,这个时候我们就要用到max-width这个属性了. img{ max-width:10 ...

  8. 19 Using Optimizer Hints

    19.1 Overview of Optimizer Hints A hint is an instruction to the optimizer. In a test or development ...

  9. jQuery通过判断 checkbox 元素的 checked 属性,判断 checkbox是否被选中

    jQuery设置复选框的属性<input type="checkbox"/> $("input").attr("checked" ...

  10. 正则神器,RegexBuddy

    解释 转换 测试匹配 使用帮助 正则图书馆 转为PHP案例 功能强大,虽然是英文的!挺不错的~