- public class CasSsoUtil {
- private static Logger logger = Logger.getRootLogger();
- //private static final String attrNameRegex = "name=\\"(.*?)\\"";
- //private static final String attrValueRegex = "value=\\"(.*?)\\"";
- private static final Pattern attrNamePattern = Pattern.compile("name=\\"(.*?)\\"");
- private static final Pattern attrValuePattern = Pattern.compile("value=\\"(.*?)\\"");
- private static String logMsgFlag = "CAS SSO for desktop application:";
- public static String CUSTOM_HTTP_STATUS = "custom_http_status_";//用于区分本应用与http协议定义的状态码
- public static String HTTP_STATUS = "http_status_";//与上面的相反
- /**
- * 用于实现桌面应用在cas server进行登录认证
- * act参数说明
- * 1:需要提取cas登录页面隐藏域的数据再次提交登录操作
- * 2:已经返回了json数据
- * 3:需要在返回的新url重新进行一次跳转操作
- * jsessionid 包含“JSESSIONID=”前缀
- */
- public static Map<String, Object> apiSubmitForm(String postUrl, NameValuePair[] nameValuePairs, int act, String jsessionid) {
- Map<String, Object> result = new HashMap<String, Object>();
- PostMethod postMethod = new PostMethod(postUrl);
- if (null != nameValuePairs)
- {
- postMethod.setRequestBody(nameValuePairs);
- }
- if (act == 1) {
- } else {
- if (jsessionid != null && !"".equals(jsessionid))
- postMethod.addRequestHeader("Cookie", jsessionid);
- }
- postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
- postMethod.addRequestHeader("Connection", "keep-alive");
- postMethod.addRequestHeader("Cache-Control", "max-age=0");
- postMethod.addRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
- postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.72 Safari/537.36");
- postMethod.addRequestHeader("Accept-Encoding", "gzip,deflate,sdch");
- postMethod.addRequestHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
- HttpClient clients = new HttpClient();
- BufferedReader rd = null;
- JSONObject jsonObj = null;
- try
- {
- int status = clients.executeMethod(postMethod);
- result.put("http_status", status);
- if (status == 200)
- {
- rd = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream(), "UTF-8"));
- StringBuffer stringBuffer = new StringBuffer();
- String line;
- while ((line = rd.readLine()) != null)
- {
- stringBuffer.append(line);
- }
- rd.close();
- if (null != stringBuffer)
- {
- String bufferStr = stringBuffer.toString();
- try {
- jsonObj = net.sf.json.JSONObject.fromObject(bufferStr);
- } catch (Exception e) {
- }
- if (jsonObj == null || "".equals(jsonObj) || "null".equals(jsonObj))
- {
- Map<String, Object> resMap = parseResponseHtml(bufferStr);
- result.put("act", "1");
- result.put("formData", resMap.get("formData"));
- result.put("JSESSIONID", resMap.get("JSESSIONID"));
- }
- else
- {
- jsonObj.put("state", status);
- result.put("act", "2");
- result.put("jsonData", jsonObj);
- }
- }
- }
- Header locationHeader = postMethod.getResponseHeader("location");
- if (locationHeader != null)
- {
- result.put("act", "3");//需要在新的url上跳转
- result.put("locationHeader", locationHeader.getValue());
- }
- } catch (Exception e) {
- e.printStackTrace();
- logger.error(logMsgFlag, e);
- result.put("act", "-1");// 异常
- } finally {
- postMethod.releaseConnection();//释放连接
- try {
- if (rd != null) rd.close();
- } catch (IOException e) {
- e.printStackTrace();
- logger.error(logMsgFlag, e);
- }
- }
- return result;
- }
- /**
- * 根据传入的url返回响应内容
- * @param url
- * @param param
- * @return
- */
- public static String getPostResponse(String url, NameValuePair[] param) {
- return getPostResponse(url, param, null);
- }
- /**
- * 根据传入的url返回响应内容
- * @param url
- * @param param
- * @param jsessionid 不包含“JSESSIONID=”前缀
- * @return
- */
- public static String getPostResponse(String url, NameValuePair[] param, String jsessionid) {
- String response = null;
- PostMethod postMethod = new PostMethod(url);
- HttpClient client = new HttpClient();
- if (jsessionid != null && !"".equals(jsessionid))
- postMethod.addRequestHeader("Cookie", "JSESSIONID="+jsessionid);
- postMethod.setRequestBody(param);
- BufferedReader rd = null;
- try
- {
- int statusCode = client.executeMethod(postMethod);
- //状态码为301,302则需要跳转页面操作
- if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
- {
- Header locationHeader = postMethod.getResponseHeader("location");
- String location = null;
- if (locationHeader != null)
- {
- location = locationHeader.getValue();
- response = getPostResponse(location, param);// 用跳转后的页面重新请求。
- }
- }
- else if (statusCode == HttpStatus.SC_OK)//200 ok
- {
- rd = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream(), "UTF-8"));
- StringBuffer stringBuffer = new StringBuffer();
- String line;
- while ((line = rd.readLine()) != null)
- {
- stringBuffer.append(line);
- }
- response = stringBuffer.toString();
- }
- else
- {
- response = getHttpStatus(statusCode);
- }
- } catch (IOException ex) {
- ex.printStackTrace();
- logger.error(logMsgFlag, ex);
- } finally {
- postMethod.releaseConnection();//释放连接
- try {
- if(rd != null) rd.close();
- } catch (IOException e) {
- e.printStackTrace();
- logger.error(logMsgFlag, e);
- }
- }
- return response;
- }
- /**
- * 从表单标签的action属性中提取jsessionid
- * @param form_action
- * @return
- */
- public static String getJsessionid(String form_action) {
- if (form_action == null)
- return form_action;
- int questionMarkIndex = form_action.indexOf("?");
- int semicolonIndex = form_action.indexOf(";");
- if (questionMarkIndex != -1)
- form_action = form_action.substring(0, questionMarkIndex);
- String jsessionid = null;
- if (semicolonIndex != -1)
- jsessionid = form_action.substring(semicolonIndex + 1, form_action.length()).toUpperCase();
- return jsessionid;
- }
- /**
- * 用于在抓取到的网页中提取表单数据:node.getAttributes()保存了html数据
- * @param node
- * @param params
- * @return
- */
- public static Map<String, String> getFormData(Node node, Map<String, String> params) {
- if (node == null)
- return params;
- Node child = node.getFirstChild();
- String nameAttr;
- while (child != null)
- {
- getFormData(child, params);
- child = child.getNextSibling();
- if (child != null && "INPUT".equalsIgnoreCase(child.getNodeName()))
- {
- NamedNodeMap map = child.getAttributes();
- nameAttr = map.getNamedItem("name").toString();
- if (params != null)
- {
- if(!params.isEmpty() && params.containsKey(nameAttr))
- {
- params.put(nameAttr, map.getNamedItem("value").toString());
- }
- }
- }
- }
- return params;
- }
- /**
- * 解析从cas server返回的html内容
- * @param response
- * @return
- */
- public static Map<String, Object> parseResponseHtml(String response) {
- Map<String, Object> result = new HashMap<String, Object>();
- InputStream inputStream = null;
- try
- {
- DOMParser parser = new DOMParser();
- inputStream = new ByteArrayInputStream(response.getBytes());
- InputSource is = new InputSource(inputStream);
- try {
- parser.parse(is);
- } catch (SAXException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- Document doc = parser.getDocument();
- NodeList nodeList = doc.getElementsByTagName("form");
- Node form = nodeList.item(0);
- Map<String, String> params = new HashMap<String, String>();
- params.put("name=\\"_eventId\\"", null);
- params.put("name=\\"execution\\"", null);
- params.put("name=\\"lt\\"", null);
- if (form != null)
- {
- params = getFormData(form, params);
- Node form_action = form.getAttributes().getNamedItem("action");
- if (form_action != null)
- {
- String action = form_action.toString();
- result.put("JSESSIONID", getJsessionid(action));
- }
- }
- Map<String, String> formData = new HashMap<String, String>();
- Iterator<String> it = params.keySet().iterator();
- String attrName = null;
- String attrValue = null;
- Matcher m = null;
- while (it.hasNext())
- {
- attrName = it.next();
- m = attrNamePattern.matcher(attrName);
- if (m.find())
- {
- attrValue = params.get(attrName);// 此处需要先取了value值后再重新给attrName赋值,否则取不到数据
- attrName = m.group(1);
- if (attrValue != null && !"".equals(attrValue))
- {
- m = attrValuePattern.matcher(attrValue);
- if (m.find())
- attrValue = m.group(1);
- }
- }
- formData.put(attrName, attrValue);
- }
- result.put("formData", formData);
- } catch (Exception e) {
- e.printStackTrace();
- logger.error(logMsgFlag,e);
- } finally {
- try {
- if(inputStream != null) inputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- logger.error(logMsgFlag, e);
- }
- }
- return result;
- }
- public static String urlEncode(String str){
- try {
- str = URLEncoder.encode(str, "utf-8");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- return str;
- }
- public static String getCHttpStatus(int status) {
- return (CUSTOM_HTTP_STATUS + status);
- }
- public static String getHttpStatus(int status) {
- return (HTTP_STATUS + status);
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/3007201513275.html
来源: http://www.codesnippet.cn/detail/3007201513275.html