此文档仅仅是一个BaseCode,已做后续查阅

  项目使用IBM Platform Symphony分布式平台,所有业务处理都在这个分布式平台上计算,需求是获取这些计算机机群的运行状态,和每一个服务的的运行状态。

  这个数据来源在一个PMC的 IBM Platform Symphony本地平台上。

  通过HttpWatch工具得到登录和获取数据的Uri:

    1、http://dane55-pc:8080/platform/dealUserLogin.do

    2、http://dane55-pc:8080/symgui/login.jsp?&login=y&loginPassword=Admin&loginUserName=Admin&redirectURL=&command=login

    3、http://dane55-pc:8080/symgui/j_spring_security_check

    4、http://dane55-pc:8080/symgui/sym/resources/clusterhealth.action?rnd=1382084686523

    5、http://dane55-pc:8080/symgui/sym/application/doApplicationProperties.action?appName=symping6.1&rnd=1382076186197

  下面是处理类:

/// <summary>
/// IBM Platform Symphony Standard Edition 处理类
/// </summary>
public class IBMPlatformSymphonyStandardEdition
{
private bool _isLogin;
/// 设置和获取登录状态
public bool IsLogin
{
get { return _isLogin; }
set { _isLogin = value; }
}
/// 登录失败后重定向的Uri
private string _baseUri = string.Empty; private CookieContainer _container = new CookieContainer(); private Encoding _encoding = new UTF8Encoding(); private HttpWebRequest _webRequest; private HttpWebResponse _webResponse; private string _postData = string.Empty; private byte[] _data = new byte[]; private string _hostName = string.Empty, _hostPort = string.Empty;
/// 构造函数
public IBMPlatformSymphonyStandardEdition()
{
this._hostName = "dane55-pc";
this._hostPort = "";
this._baseUri = "http://dane55-pc:8080/symgui/framework/login/toLogin.action";
this._isLogin = false;
}
/// 构造函数 指定主机名称和端口
public IBMPlatformSymphonyStandardEdition(string hostName, string hostPort)
{
this._hostName = hostName;
this._hostPort = hostPort;
this._baseUri = "http://" + hostName + ":" + hostPort + "/symgui/framework/login/toLogin.action";
this._isLogin = false;
}
/// 登录
public bool LoginSymphony(string userName, string userPass)
{
try
{
#region http://dane55-pc:8080/platform/dealUserLogin.do _postData = "command=login&loginUserName=" + userName + "&redirectURL=&login=y&loginPassword=" + userPass;
_data = _encoding.GetBytes(_postData);
_webRequest = (HttpWebRequest)WebRequest.Create("http://" + _hostName + ":" + _hostPort + "/platform/dealUserLogin.do");
_webRequest.Method = "Post";
_webRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
_webRequest.ContentLength = _data.Length;
_webRequest.KeepAlive = true;
_webRequest.CookieContainer = _container;
_webRequest.GetRequestStream().Write(_data, , _data.Length);
_webResponse = (HttpWebResponse)_webRequest.GetResponse();
#endregion #region http://dane55-pc:8080/symgui/login.jsp?&login=y&loginPassword=Admin&loginUserName=Admin&redirectURL=&command=login string uri = "http://" + _hostName + ":" + _hostPort + "/symgui/login.jsp?&login=y&loginPassword=" + userPass + "&loginUserName=" + userName + "&redirectURL=&command=login";
_webRequest = (HttpWebRequest)WebRequest.Create(uri);
_webRequest.Method = "GET";
_webRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
_webRequest.KeepAlive = true;
_webRequest.CookieContainer = _container;
_webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)";
_webResponse = (HttpWebResponse)_webRequest.GetResponse();
StreamReader readers = new StreamReader(_webResponse.GetResponseStream(), Encoding.UTF8);
string contents = readers.ReadToEnd();
readers.Close();
readers.Dispose();
string j_username = string.Empty;
string j_password = string.Empty;
Regex _regex = new Regex(@"(?is)<input[^/>]*id=(?<id>\s*)[^/>]*value(?<v>\s*)[^/>]*/>");
if (_regex.IsMatch(contents))
{
MatchCollection collection = _regex.Matches(contents);
if (collection[].ToString().IndexOf("name=\"j_username\"") > -)
{
_regex = new Regex("value=\"(.+?)\"");
if (_regex.IsMatch(collection[].ToString()))
{
Match aas = _regex.Match(collection[].ToString());
j_username = aas.ToString().Replace("value=\"", "").Replace("\"", "");
}
}
if (collection[].ToString().IndexOf("name=\"j_username\"") > -)
{
_regex = new Regex("value=\"(.+?)\"");
if (_regex.IsMatch(collection[].ToString()))
{
Match aas = _regex.Match(collection[].ToString());
j_password = aas.ToString().Replace("value=\"", "").Replace("\"", "");
}
} }
#endregion #region http://dane55-pc:8080/symgui/j_spring_security_check string uri1 = "http://" + this._hostName + ":" + this._hostPort + "/symgui/j_spring_security_check";
_webRequest = (HttpWebRequest)WebRequest.Create(uri1);
_postData = "j_password=" + j_password + "&j_username=" + j_username;
_data = _encoding.GetBytes(_postData);
_webRequest.Method = "POST";
_webRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
_webRequest.KeepAlive = true;
_webRequest.CookieContainer = _container;
_webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)";
_webRequest.GetRequestStream().Write(_data, , _data.Length);
_webResponse = (HttpWebResponse)_webRequest.GetResponse();
if (_webRequest.Address.AbsoluteUri == _baseUri) return false;
#endregion
}
catch (Exception)
{
throw new Exception("登录Symphony平台发生异常");
}
return true;
}
/// 获取平台机群数据以及运行状态
public Masters GetHostData()
{
if (!this._isLogin) return null;
string url = "http://" + _hostName + ":" + _hostPort + "/symgui/sym/resources/clusterhealth.action?rnd=" + this.GetRnd();
return GetHostData(url);
}
/// 获取平台机群数据以及运行状态
public Masters GetHostData(string url)
{
try
{
Masters master = null;
if (!this._isLogin) return null;
_webRequest = (HttpWebRequest)WebRequest.Create(url);
_webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
_webRequest.Method = "GET";
_webRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
_webRequest.ContentLength = ;
_webRequest.KeepAlive = true;
_webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)";
_webRequest.CookieContainer = _container;
_webResponse = (HttpWebResponse)_webRequest.GetResponse();
StreamReader reader = new StreamReader(_webResponse.GetResponseStream(), Encoding.UTF8);
string szJson = reader.ReadToEnd();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
{
Masters obj = Activator.CreateInstance<Masters>();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
master = (Masters)serializer.ReadObject(ms);
}
return master;
}
catch (Exception)
{
throw new Exception("获取Symphony平台机群信息异常");
}
}
/// 获取指定服务名称运行状态信息
public ApplicationProperties GetApplicationPropertiesData(string appName)
{
try
{
string url = "http://" + _hostName + ":" + _hostPort + "/symgui/sym/application/doApplicationProperties.action?appName=" + appName + "&rnd=" + GetRnd();
ApplicationProperties application = null;
if (!this._isLogin) return null;
_webRequest = (HttpWebRequest)WebRequest.Create(url);
_webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
_webRequest.Method = "GET";
_webRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
_webRequest.ContentLength = ;
_webRequest.KeepAlive = true;
_webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)";
_webRequest.CookieContainer = _container;
_webResponse = (HttpWebResponse)_webRequest.GetResponse();
StreamReader reader = new StreamReader(_webResponse.GetResponseStream(), Encoding.UTF8);
string szJson = reader.ReadToEnd();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
{
ApplicationProperties obj = Activator.CreateInstance<ApplicationProperties>();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
application = (ApplicationProperties)serializer.ReadObject(ms);
}
return application;
}
catch (Exception)
{
throw new Exception("获取Symphony平台ApplicationProperties信息异常");
}
}
/// 防止获取浏览器缓存数据
private string GetRnd()
{
DateTime oldTime = new DateTime(, , );
TimeSpan span = DateTime.Now.Subtract(oldTime);
return span.TotalMilliseconds.ToString("F0");
}
}
  public class ApplicationProperties
{
public string customerStore;
public string dir;
public int pageSize;
public List<Records> records;
public ReturnMsgs returnMsgs;
public string sort;
public int startIndex;
public int totalRecords;
} public class Records
{
public string defaultValue;
public string key;
public string value;
}
/// 查询索引器
public class RecordsIndexer
{
IDictionary<string, string> _dictionary;
public RecordsIndexer(List<Records> recordsList)
{
_dictionary = new Dictionary<string, string>();
foreach (Records records in recordsList)
{
_dictionary.Add(records.key, records.value);
}
}
public string this[string key]
{
get
{
if (key == "")
{
return null;
}
else
{
return _dictionary[key];
}
}
set
{
if (key != "")
{
_dictionary[key] = value;
}
}
}
} public class ReturnMsgs
{
public List<String> failure;
public string success;
}
    [Serializable]
public class Master
{
public string hostName;
public string mem;
public string io;
public string pg;
public string ncpus;
public string hostStatus;
public string type;
public string swp;
public string ut;
} [Serializable]
public class ClusterInfo
{
public int unavail_hosts;
public string clusterName;
public int ut_hosts0;
public int ut_hosts1;
public int ut_hosts2;
public int ok_hosts;
public int ut_hosts3;
public int ut_hosts4;
public int ut_hosts5;
public int ut_hosts6;
public int ut_hosts7;
public int ut_hosts8;
public int all_hosts;
public int scavenging_closed_hosts;
public int ut_hosts9;
public int closed_hosts;
public int scavenging_ok_hosts;
} [Serializable]
public class AllHostGroups
{
public string InternalResourceGroup;
public string ComputeHosts;
public string ManagementHosts;
} [Serializable]
public class Masters
{
public List<Master> MasterList = new List<Master>(); public List<String> candidateHosts = new List<string>(); public ClusterInfo ClusterInfo = new ClusterInfo(); public Master sdHost = new Master(); public List<String> allHosts = new List<string>(); public Master MasterHost = new Master(); public AllHostGroups allhostgroups = new AllHostGroups();
}

  运行测试:  

       static IBMPlatformSymphonyStandardEdition edtion = new IBMPlatformSymphonyStandardEdition();
static void Main(string[] args)
{
bool _isBool = edtion.LoginSymphony("Admin", "Admin");
if (!_isBool)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine("登录失败,正在重新登录");
Console.BackgroundColor = ConsoleColor.Black;
}
else
{
edtion.IsLogin = _isBool;
Console.BackgroundColor = ConsoleColor.Green;
Console.WriteLine("登录成功");
Console.BackgroundColor = ConsoleColor.Black;
Masters _masters = edtion.GetHostData();
ApplicationProperties applications = edtion.GetApplicationPropertiesData("symping6.1");
foreach (var item in _masters.MasterList)
{
Console.WriteLine(item.hostName);
}
foreach (Records item in applications.records)
{
RecordsIndexer indexer = new RecordsIndexer(applications.records);
Console.BackgroundColor = ConsoleColor.Green;
Console.WriteLine(indexer["appName"]);
Console.BackgroundColor = ConsoleColor.Black;
Console.WriteLine(item.value);
} }
}

  

HttpWebRequest 模拟网站登录获取数据的更多相关文章

  1. cookielib和urllib2模块相结合模拟网站登录

    1.cookielib模块 cookielib模块的主要作用是提供可存储cookie的对象,以便于与urllib2模块配合使用来访问Internet资源.例如可以利用 本模块的CookieJar类的对 ...

  2. c# winform实现网页上用户自动登陆,模拟网站登录

    using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO ...

  3. Java模拟网站登录02【转载】

    如何用Java代码模拟一些如百度.QQ之类的网站登录?有两个方式,一是发送模拟请求,二是模拟浏览器操作,而这两种方式恰好在Java有开源实现,在这里介绍一个工具包,它是家喻户晓的HttpClient. ...

  4. 第三百三十三节,web爬虫讲解2—Scrapy框架爬虫—Scrapy模拟浏览器登录—获取Scrapy框架Cookies

    第三百三十三节,web爬虫讲解2—Scrapy框架爬虫—Scrapy模拟浏览器登录 模拟浏览器登录 start_requests()方法,可以返回一个请求给爬虫的起始网站,这个返回的请求相当于star ...

  5. 十二 web爬虫讲解2—Scrapy框架爬虫—Scrapy模拟浏览器登录—获取Scrapy框架Cookies

    模拟浏览器登录 start_requests()方法,可以返回一个请求给爬虫的起始网站,这个返回的请求相当于start_urls,start_requests()返回的请求会替代start_urls里 ...

  6. C#如何HttpWebRequest模拟登陆,获取服务端返回Cookie以便登录请求后使用

    public static string GetCookie(string requestUrlString, Encoding encoding, ref CookieContainer cooki ...

  7. 利用 cookie 模拟网站登录

    import urllib import urllib2 import cookielib filename = 'cookie.txt' \#声明一个MozillaCookieJar对象实例来保存c ...

  8. Java模拟网站登录

    web登陆无非就是网页获取,cookie 的管理,post和get方式的模拟. 1.网页内容获取 java.io.InputStream in; java.net.URL url = new java ...

  9. PHP 之 CURL 模拟登陆并获取数据

    1.CURL模拟登陆的流程和步骤 2.tempnam 创建一个临时文件 3.使用CURL模拟登陆到PHP100论坛 <?php $cookie_file = tempnam('./temp',' ...

随机推荐

  1. hack:选择符前缀法,样式属性前缀法

    选择符前缀法 <style> *html .test{width:100px;} /*only for IE6*/ *+html .test{width:100px;}/*for IE6 ...

  2. linux下的5款桌面环境

    以前都用Ubuntu,没有换过桌面环境,不会换,也担心换了不会(真是有病,担心用不习惯,还不如回去用windows) ubuntu 默认的是Unity,用过一段不长的时间,恩,说不出来有什么不好的,也 ...

  3. 读【10问PHP程序员】 有感

    http://bbs.phpchina.com/thread-174331-1-1.html 看到前人的文章,总结自己的学习心得,颇有感悟,下面是自己的总结,平时就拿出来多问问自己.1.上了十几年的学 ...

  4. Java 八大类型、String和 StringBuffer

    1. 八大类型 类型 封装类 占字节 int;       Integer;   4 short;         Short;            2 byte;          Byte;   ...

  5. [ Android 五种数据存储方式之二 ] —— 文件存储数据

    关于文件存储,Activity提供了openFileOutput()方法可以用于把数据输出到文件中,具体的实现过程与在J2SE环境中保存数据到文件中是一样的. 文件可用来存放大量数据,如文本.图片.音 ...

  6. hadoop学习笔记--集群搭建

    注:大家常说的ssh其实就是一个免密码访问的东西,为了简化操作的,不用每次访问其他节点重新输入密码.但是要想配置如下: .在每台机器上执行 ssh-keygen -t rsa,连敲三次回车键(即设置空 ...

  7. ORA-01555经典错误

    --创建undo表空间时固定表空间的大小 sys@TDB112>create undo tablespace undo_small 2  datafile'/u01/app/oracle/ora ...

  8. 小试 Ninja

    Ninja 是最近冒出来的一个 build system,它很像 make,然而效率更高,对大项目支持更好.当然我用 Ninja 和效率无关(我又没有那种有几百个中间目标的 C++ 项目要 build ...

  9. HTML5本地存储 localStorage 和 sessionStorage 的基本用法及属性

    localStorage 和 sessionStorage 的用法都是本地的存储和获取 但他们又有所区别, 1, sessionStorage 是一个短暂的本地存数,它会随着浏览器的刷新和关闭而消失, ...

  10. 玩转spring boot——结合阿里云持续交付

    前言 在互联网项目中,项目测试.部署往往需要花费大量时间.传统方式是在本地打包.测试完毕程序,然后通过ftp上传至服务器,再把测试的配置文件修改为生产环境的配置文件,最后重新运行服务.这一过程如果交给 ...