public static IMusic[] SearchMusic(MusicSource type, string content) { try { if (type == MusicSource.Netease) { string url = "http://blog.ylz1.cn/page/music/api.php"; byte[] commit = Encoding.UTF8.GetBytes($"types=search&count=10&source=netease&pages=1&name={content}"); byte[] data = HttpWebClient.Post(url, commit); NeteaseMusic[] infos = JsonConvert.DeserializeObject <NeteaseMusic[]>(Encoding.UTF8.GetString(data)); return(infos); } else if (type == MusicSource.Kugou) { string url = "http://blog.ylz1.cn/page/music/api.php"; byte[] commit = Encoding.UTF8.GetBytes($"types=search&count=10&source=kugou&pages=1&name={content}"); byte[] data = HttpWebClient.Post(url, commit); KugouMusic[] infos = JsonConvert.DeserializeObject <KugouMusic[]>(Encoding.UTF8.GetString(data)); return(infos); } else { string url = $"https://api.qq.jsososo.com/search?key={content}&pageNo=1&pageSize=10"; byte[] data = HttpWebClient.Get(url); TencentMusic[] infos = JsonConvert.DeserializeObject <TencentMusic[]>(JObject.Parse(Encoding.UTF8.GetString(data))?["data"]?["list"].ToString()); return(infos); } } catch (Exception) { return(new IMusic[0]); } }
public void Get() { HttpWebServer aHttpListener = new HttpWebServer("http://127.0.0.1:8094/"); try { aHttpListener.StartListening(x => { if (x.Request.HttpMethod == "GET") { x.SendResponseMessage("blabla"); } else { x.Response.StatusCode = 404; } }); HttpWebResponse aWebResponse = HttpWebClient.Get(new Uri("http://127.0.0.1:8094/hello/")); Assert.AreEqual(HttpStatusCode.OK, aWebResponse.StatusCode); string aResponseMessage = aWebResponse.GetResponseMessageStr(); Assert.AreEqual("blabla", aResponseMessage); } finally { aHttpListener.StopListening(); } }
public LocalUserLogonerForAccessThroughGroup(string username, string password, string groupname, IWebServer webServer) { UserName = username; Password = password; GroupName = groupname; WebServer = webServer; HttpWebClient httpWebClient = new HttpWebClient(); WebServerTestBase.LoginAsRoot(httpWebClient, webServer); HttpResponseHandler webResponse; webResponse = httpWebClient.Post("http://localhost:" + WebServer.Port + "/Users/UserDB?Method=CreateUser", new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("displayName", username), new KeyValuePair<string, string>("password", password), new KeyValuePair<string, string>("assignSession", false.ToString())); Assert.AreEqual(HttpStatusCode.Created, webResponse.StatusCode, "Bad status code"); webResponse = httpWebClient.Post("http://localhost:" + WebServer.Port + "/Users/UserDB?Method=CreateGroup", new KeyValuePair<string, string>("groupname", groupname), new KeyValuePair<string, string>("username", "root")); Assert.AreEqual(HttpStatusCode.Created, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(groupname + " created", webResponse.AsString(), "Unexpected response"); webResponse = httpWebClient.Get("http://localhost:" + WebServer.Port + "/Users/UserDB", new KeyValuePair<string, string>("Method", "AddUserToGroup"), new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("groupname", groupname)); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(username + " added to " + groupname, webResponse.AsString(), "Unexpected response"); }
protected string getHttpProxy(string url, Dictionary <string, string> header = null) { try { WebHeaderCollection webHeaderCollection = new WebHeaderCollection(); CookieCollection cookies = new CookieCollection(); string accept = ""; if (header != null) { foreach (KeyValuePair <string, string> kv in header) { if (kv.Key == "Accept") { accept = kv.Value; } else { webHeaderCollection.Add(kv.Key, kv.Value); } } } if (int.Parse(getOptions()["EnableProxy"]) > 0) { return(Encoding.UTF8.GetString(HttpWebClient.Get(url, "", "", accept, 0, ref cookies, ref webHeaderCollection, new WebProxy(getProxyAddress(), getProxyPort()), Encoding.UTF8))); } else { return(Encoding.UTF8.GetString(HttpWebClient.Get(url, "", "", accept, 0, ref cookies, ref webHeaderCollection, null, Encoding.UTF8))); } } catch (WebException) { return(""); } }
public string Get(string str) { string result; string Commandconfig = ini.ReadConfiguration("Command"); int t = Commandconfig.Length; string left = str.Substring(0, t); string right = str.Substring(str.Length - t); string url = ini.ReadConfiguration("Url"); byte[] get = HttpWebClient.Get(url + right); string Json = Encoding.UTF8.GetString(get); Root rt = JsonConvert.DeserializeObject <Root>(Json); int g; g = rt.code; if (g == 1) { result = "入库成功!\n内容为:" + right; return(result); } else { result = "入库失败!"; return(result); } //return Json; }
/// <summary> /// 获取排行榜 /// </summary> /// <param name="mode">指定排行榜的类型 可选参数:day-日榜 week-周榜 month-月榜...详见https://api.imjad.cn/pixiv_v2.md</param> /// <param name="page">页数,从1开始,默认为1</param> /// <returns></returns> public static string GetRank(string mode, int page = 1) { string url = $"https://api.imjad.cn/pixiv/v2/?type=rank&mode={mode}&page={page}"; string returnstr = Encoding.UTF8.GetString(HttpWebClient.Get(url)); Pixiv_Rank rank = JsonConvert.DeserializeObject <Pixiv_Rank>(returnstr); return($"[CQ:at,file=Empty.png]"); }
public void TestEnforcementOfActionPermissions() { HttpWebClient httpWebClient = new HttpWebClient(); HttpResponseHandler webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/Users/root"); Assert.AreEqual(HttpStatusCode.Unauthorized, webResponse.StatusCode, "Bad status code"); }
public void TestBypassOfActionPermissions() { HttpWebClient httpWebClient = new HttpWebClient(); HttpResponseHandler webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/Users/root?BypassActionPermission=true"); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); }
public void TestCanGetOpenIdLandingPage() { HttpWebClient httpWebClient = new HttpWebClient(); HttpResponseHandler webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/Shell/OpenID/OpenIDLandingPage.wchtml?openid.mode=checkid_setup&openid.trust_root=&openid.identity=http%3a%2f%2flocalhost%3a1080%2fUsers%2froot.user&openid.return_to=http%3a%2f%2flocalhost%3a1080%2fUsers%2fUserDB%3fMethod%3dCompleteOpenIdLogin%26esoid.claimed_id%3dhttp%253a%252f%252flocalhost%253a1080%252fUsers%252froot.user"); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); }
private void Btn_CkUpdate_Click(object sender, RoutedEventArgs e) { progressbar_update.Visibility = Visibility.Visible; string update = Encoding.UTF8.GetString(HttpWebClient.Get("https://gitee.com/Hellobaka/LoliconApiSetuBot/raw/master/New.json")); var updateinfo = JsonConvert.DeserializeObject <Update>(update); progressbar_update.Visibility = Visibility.Hidden; ShowUpdateContent(updateinfo); }
public void TestIgnoreUnknownActionPermissions() { HttpWebClient httpWebClient = new HttpWebClient(); HttpResponseHandler webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/Users/root?Action=Abc"); Assert.AreEqual(HttpStatusCode.InternalServerError, webResponse.StatusCode, "Bad status code"); Assert.AreEqual("ObjectCloud does not support the action \"Abc\" for files of type \"directory\"", webResponse.AsString(), "Unexpected response"); }
public void TestGarbageCollection() { try { IWebConnection webConnection = null; WebServer.Stop(); WebServer.StartServer(); EventHandler<IWebServer, EventArgs<IWebConnection>> webConnectionStarted = delegate(IWebServer webServer, EventArgs<IWebConnection> e) { webConnection = e.Value; }; try { WebServer.WebConnectionStarting += webConnectionStarted; HttpWebClient httpWebClient = new HttpWebClient(); HttpResponseHandler webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/"); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.IsNotNull(webResponse.AsString(), "Nothing returned"); Assert.IsNotNull(webConnection, "IWebConnection not set by delegate"); } finally { WebServer.WebConnectionStarting -= webConnectionStarted; } WebServer.Stop(); // Wait for the conneciton to close while (webConnection.Connected) Thread.Sleep(25); WeakReference weakReference = new WeakReference(webConnection); webConnection = null; DateTime stopTime = DateTime.Now.AddSeconds(5); while (weakReference.IsAlive) { Thread.Sleep(25); GC.Collect(); Assert.IsTrue(DateTime.Now < stopTime, "Took too long to garbage collect the IWebConnection"); } } finally { WebServer.StartServer(); } }
protected override string getHttp(string room) { try { return(Encoding.UTF8.GetString(HttpWebClient.Get("https://api.kingkongapp.com/webapi/v1/search/global?keyword=" + room))); } catch (Exception) { return(""); } }
protected override string getHttp(string room) { try { //WebHeaderCollection webHeaderCollection = new WebHeaderCollection(); //CookieCollection cookies = new CookieCollection(); string content = Encoding.UTF8.GetString(HttpWebClient.Get("http://open.douyucdn.cn/api/RoomApi/room/" + room)); //, "", ref cookies, ref webHeaderCollection, new WebProxy("127.0.0.1", 8888), Encoding.UTF8)); return(content); } catch (Exception) { return(""); } }
protected override string getHttp(string room) { try { return(Encoding.UTF8.GetString(HttpWebClient.Get("https://api.live.bilibili.com/xlive/web-room/v1/index/getInfoByRoom?room_id=" + room))); } catch (Exception) { return(""); } }
public void TestErrorInShellSetting() { string newfileName = "TestUseText" + SRandom.Next().ToString() + ".badDNE"; HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "text"); HttpResponseHandler webResponse = httpWebClient.Get("http://localhost:" + WebServer.Port + "/" + newfileName); Assert.AreEqual(HttpStatusCode.InternalServerError, webResponse.StatusCode, "Bad status code"); Assert.AreEqual("ObjectCloud is not configured to handle files of type badDNE", webResponse.AsString(), "Unexpected value"); }
public void TestAddUserToGroup() { HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); HttpResponseHandler webResponse; string groupname = "testgroup" + SRandom.Next(100000).ToString(); webResponse = httpWebClient.Post("http://localhost:" + WebServer.Port + "/Users/UserDB?Method=CreateGroup", new KeyValuePair<string, string>("groupname", groupname), new KeyValuePair<string, string>("username", "root")); Assert.AreEqual(HttpStatusCode.Created, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(groupname + " created", webResponse.AsString(), "Unexpected response"); string username = "******" + SRandom.Next(100000).ToString(); webResponse = httpWebClient.Post("http://localhost:" + WebServer.Port + "/Users/UserDB?Method=CreateUser", new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("displayName", username), new KeyValuePair<string, string>("password", "password"), new KeyValuePair<string, string>("assignSession", false.ToString())); Assert.AreEqual(HttpStatusCode.Created, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(username + " created", webResponse.AsString(), "Unexpected response"); webResponse = httpWebClient.Post("http://localhost:" + WebServer.Port + "/Users/UserDB?Method=AddUserToGroup", new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("groupname", groupname)); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(username + " added to " + groupname, webResponse.AsString(), "Unexpected response"); webResponse = httpWebClient.Get("http://localhost:" + WebServer.Port + "/Users/UserDB", new KeyValuePair<string, string>("Method", "GetUsersGroups"), new KeyValuePair<string, string>("username", username)); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); JsonReader jsonReader = webResponse.AsJsonReader(); object[] result = jsonReader.Deserialize<object[]>(); Assert.AreEqual(1, result.Length, "Wrong number of groups"); Assert.IsInstanceOf<Dictionary<string, object>>(result[0], "Wrong type decoded"); Dictionary<string, object> group = (Dictionary<string, object>)result[0]; Assert.AreEqual(groupname, group["Name"], "Wrong name returned"); }
public void TestLargeBinaryFile() { string newfileName = "TestLargeBinaryFile" + SRandom.Next().ToString(); HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "binary"); byte[] toWrite = SRandom.NextBytes(1024 * 1024 * 3); for (int requestCtr = 0; requestCtr < 3; requestCtr++) { HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=WriteAll"); webRequest.KeepAlive = true; webRequest.UnsafeAuthenticatedConnectionSharing = true; webRequest.Method = "POST"; webRequest.ContentType = "application/binary"; webRequest.CookieContainer = httpWebClient.CookieContainer; webRequest.ContentLength = toWrite.Length; // Write the request webRequest.GetRequestStream().Write(toWrite, 0, toWrite.Length); using (HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse()) { Assert.AreEqual(HttpStatusCode.Accepted, httpWebResponse.StatusCode, "Bad status code"); } byte[] written = FileHandlerFactoryLocator.FileSystemResolver.ResolveFile("/" + newfileName).CastFileHandler<IBinaryHandler>().ReadAll(); Assert.IsTrue(Enumerable.Equals(toWrite, written), "Data written incorrectly"); HttpResponseHandler webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/" + newfileName, new KeyValuePair<string, string>("Method", "ReadAll")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.IsTrue(Enumerable.Equals(toWrite, webResponse.AsBytes()), "Unexpected value"); } }
public string Getjson(string city) { string msg = ""; byte[] getbyte = HttpWebClient.Get("https://xiaojieapi.cn/API/epidemic.php?city=" + city); string getJson = Encoding.UTF8.GetString(getbyte); //Root rt = JsonConvert.DeserializeObject<Root>(getJson); //Total tal = JsonConvert.DeserializeObject<Total>(getJson); string json = getJson ; JObject root = JObject.Parse(json); JObject total = root["total"].Value<JObject>(); var keys = total.GetEnumerator(); while (keys .MoveNext ()) { msg += keys.Current.ToString()+"\r"; } var re = msg; re.Replace("[", ""); re.Replace("]", ""); return re; }
public static string Ping(string msg) { if (!IsOpen()) { return("未开启!"); } string ip = StrongString.GetRight(msg.Replace(" ", ""), "ping"); Ping p = new Ping(); PingReply reply = p.Send(ip); bool isDomain = IsDomain(ip); //获取地址 byte[] data = HttpWebClient.Get($"https://www.ip.cn/?ip={reply.Address}"); string str = Encoding.UTF8.GetString(data); string address = StrongString.Between(str, "所在地理位置:<code>", "</code>"); string result = (isDomain ? $"域名:{ip}\n" : "") + $"IP:{reply.Address}\n延迟:{reply.RoundtripTime}ms\n地址:{address}\n当前时间:{DateTime.Now}"; return(result); }
static void Main(string[] args) { HttpWebResponseResult httpWebResponseResult = null; HttpWebClient httpWebClient = new HttpWebClient(); httpWebClient.Headers.Add("Referer", "http://localhost"); httpWebClient.IsTraceEnabled = true; //Example No.1 multipart/form-data POST reqeust String url = "http://localhost:53090/upload/uploadfile"; byte[] byteFiles = null; using (FileStream fs = new FileStream(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "01.jpg"), FileMode.Open, FileAccess.Read)) { byteFiles = new byte[fs.Length]; fs.Read(byteFiles, 0, byteFiles.Length); } httpWebClient.SetField("StorageFile.Title", "title01", true); httpWebClient.SetField("StorageFile.Summary", "summary01", true); httpWebClient.SetField("filedata", byteFiles, "001.jpg", String.Empty); httpWebResponseResult = httpWebClient.Post(url); TraceInfo(httpWebResponseResult); //Example No.2 application/x-www-form-urlencoded POST reqeust url = "http://localhost:53090/passport/logon"; httpWebClient.SetField("LogonInfo.ValidateCode", "gvzwb"); httpWebClient.SetField("LogonInfo.User.Username", "sanxia123"); httpWebClient.SetField("LogonInfo.User.Password", "Yc123703"); httpWebClient.SetField("LogonInfo.IsPersistentCookie", "false"); httpWebResponseResult = httpWebClient.Post(url); TraceInfo(httpWebResponseResult); //Example No.3 GET reqeust url = "http://localhost:53090/content/oauth.html"; httpWebClient.SetField("a", "1"); httpWebResponseResult = httpWebClient.Get(url); TraceInfo(httpWebResponseResult); System.Console.ReadKey(true); }
private string GetJson(string name) { try { string url = "https://api.mikualpha.com/kancolle/KanColleTime.php?v=" + version + "&name=" + name + "&group=" + group.ToString(); string json = Encoding.Default.GetString(HttpWebClient.Get(url)); if (json.Contains("Error: ")) { string temp = json.Substring(json.IndexOf(":") + 2); CQApi.SendGroupMessage(group, temp); return(""); } if (!json.Contains("[")) { return(""); } return(json); } catch (MissingMethodException) { return(""); } }
public void Get_NotFound() { HttpWebServer aHttpListener = new HttpWebServer("http://127.0.0.1:8094/"); try { aHttpListener.StartListening(x => { if (x.Request.HttpMethod == "GET") { x.Response.StatusCode = 404; } }); Assert.Throws <WebException>(() => HttpWebClient.Get(new Uri("http://127.0.0.1:8094/hello/"))); } finally { aHttpListener.StopListening(); } }
public OpenIDLogonerThroughObjectCloud(string name, string password, IWebServer secondWebServer) { Name = name; Password = password; SecondWebServer = secondWebServer; HttpWebClient httpWebClient = new HttpWebClient(); WebServerTestBase.LoginAsRoot(httpWebClient, SecondWebServer); HttpResponseHandler webResponse; webResponse = httpWebClient.Post("http://localhost:" + SecondWebServer.Port + "/Users/UserDB?Method=CreateUser", new KeyValuePair<string, string>("username", name), new KeyValuePair<string, string>("displayName", name), new KeyValuePair<string, string>("password", password)); Assert.AreEqual(HttpStatusCode.Created, webResponse.StatusCode, "Bad status code"); webResponse = httpWebClient.Get("http://localhost:" + SecondWebServer.Port + "/Users/" + name + ".user"); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Thread.Sleep(2000); }
public string Handler(CQGroupMessageEventArgs e, Base_SQLHelper.SQLHelperData b) { String Order = e.Message.Text.Trim().Substring(22).Trim(); String Music = Order.Substring(Order.IndexOf("#") + 1); String raw; //return Music; if (!SQL.UserExists(b, e.FromQQ)) { return("不认识的孩子呢"); } try { raw = Encoding.Default.GetString(HttpWebClient.Get("http://music.163.com/api/search/pc?limit=1&type=1&s=" + Music, UA)); } catch { return("Network ERR"); } try { reader = new JsonTextReader(new StringReader(raw)); while (reader.Read()) { if (reader.TokenType.ToString() == "PropertyName" && reader.Value.ToString() == "id") { reader.Read(); SQL.AddFavorEveryChat(b, e.FromQQ); return(CQApi.CQCode_Music(int.Parse(reader.Value.ToString()), Native.Sdk.Cqp.Enum.CQMusicType.Netease).ToString()); } } return("Music NOT found"); } catch { return("Results ERR"); } }
private static OLD_Endpoints LoadEndpoints(string openId) { HttpWebClient httpWebClient = new HttpWebClient(); HttpResponseHandler response = httpWebClient.Get(openId); // If there was an error if (response.StatusCode != System.Net.HttpStatusCode.OK) throw new Exception(); return new OLD_Endpoints(openId, response.AsString()); }
public void TestUseText() { string newfileName = "TestUseText" + SRandom.Next().ToString(); HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "text"); HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=WriteAll"); webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.CookieContainer = httpWebClient.CookieContainer; string text = "the\ntext\nto\nsave"; byte[] toWrite = Encoding.UTF8.GetBytes(text); webRequest.ContentLength = toWrite.Length; // Write the request webRequest.GetRequestStream().Write(toWrite, 0, toWrite.Length); using (HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse()) { Assert.AreEqual(HttpStatusCode.Accepted, httpWebResponse.StatusCode, "Bad status code"); } HttpResponseHandler webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/" + newfileName, new KeyValuePair<string, string>("Method", "ReadAll")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(text, webResponse.AsString(), "Unexpected value"); }
/// <summary> /// 爬取崩坏三公告来获取池子 /// </summary> /// <param name="opiton">寻找公告的关键字</param> public string GetPoolOnline(string opiton) { Initialize(); string blackboard = "https://www.bh3.com/news/cate/175"; try { byte[] by = HttpWebClient.Get(blackboard); string a = Encoding.UTF8.GetString(by); HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument(); for (int q = 1; q <= 10; q++) { htmlDoc.LoadHtml(a); var rootnode = htmlDoc.DocumentNode.SelectSingleNode($"/html[1]/body[1]/div[1]/div[2]/div[1]/div[2]/div[1]/div[2]/div[1]/div[2]/div[{q}]"); var url = rootnode.SelectSingleNode("a[1]").GetAttributeValue("href", ""); var Url = rootnode.SelectSingleNode("a[1]/div[2]/div[1]/div[1]"); url = $"https://www.bh3.com{url.Trim()}"; string title = HttpUtility.HtmlDecode(Url.InnerText.Trim()); if (title.Contains(opiton)) { ret_Text += $"{title} 链接:{url}\n"; byte[] by2 = HttpWebClient.Get(url); string a2 = Encoding.UTF8.GetString(by2); htmlDoc.LoadHtml(a2); if (title.Contains("精准")) { try { rootnode = htmlDoc.DocumentNode.SelectSingleNode($"/html[1]/body[1]/div[1]/div[2]/div[1]/div[2]/div[1]/div[1]/div[3]/div[2]"); var count = rootnode.ChildNodes.Count; if (count > 60) { foreach (var item in rootnode.ChildNodes) { if (item.InnerText.Contains("精准补给A为")) { //UPA var result = GetUpStaff(item.InnerText); if (result.Count == 2) { ret_Text += $"精准A UP:{result[0]} {result[1]}\n"; UPAWeapon = result[0]; UPAStigmata = result[1]; } } if (item.InnerText.Contains("精准补给B为")) { //UPB var result = GetUpStaff(item.InnerText); if (result.Count == 2) { ret_Text += $"精准B UP:{result[0]} {result[1]}\n"; UPBWeapon = result[0]; UPBStigmata = result[1]; } } if (item.InnerText.Contains("【★4武器】")) { var WeaponText = item; int weaponcount = 0; ret_Text += "池子内容:\n"; for (int i = 0; i < 8; i++) { WeaponText = WeaponText.NextSibling.NextSibling; try { List <string> WeaponList = GetItem(WeaponText.InnerText); weaponcount += WeaponList.Count; foreach (var item2 in WeaponList) { ret_Text += $"{item2}\n"; JZWeapon.Add(item2); } if (weaponcount == 7) { break; } } catch (Exception ex) { QMLog.CurrentApi.Info("崩坏三公告获取" + ex.Message + " " + ex.StackTrace + "\n"); } } } if (item.InnerText.Contains("【★4圣痕】")) { var StigmataText = item; ret_Text += "池子内容:\n"; for (int i = 0; i < 5; i++) { StigmataText = StigmataText.NextSibling.NextSibling; try { List <string> StigmataList = GetItem(StigmataText.InnerText); foreach (var item2 in StigmataList) { ret_Text += $"{item2}\n"; JZStigmata.Add(item2); } } catch (Exception ex) { QMLog.CurrentApi.Info("崩坏三公告获取" + ex.Message + " " + ex.StackTrace + "\n"); } } } } } else if (count == 16) { foreach (var item in rootnode.ChildNodes) { if (item.InnerText.Contains("精准补给A为")) { //UPA var result = GetUpStaff(item.InnerText); if (result.Count == 4) { ret_Text += $"精准A UP:{result[0]} {result[1]}\n"; UPAWeapon = result[0]; UPAStigmata = result[1]; } } if (item.InnerText.Contains("精准补给B为")) { //UPB var result = GetUpStaff(item.InnerText); if (result.Count == 4) { ret_Text += $"精准B UP:{result[2]} {result[3]}\n"; UPBWeapon = result[2]; UPBStigmata = result[3]; } } if (item.InnerText.Contains("【★4武器】")) { string[] WeaponText = item.InnerText.Split('\n'); ret_Text += "池子内容:\n"; for (int i = 0; i < WeaponText.Length - 1; i++) { try { List <string> WeaponList = GetItem(WeaponText[1 + i]); foreach (var item2 in WeaponList) { ret_Text += $"{item2}\n"; JZWeapon.Add(item2); } } catch (Exception ex) { QMLog.CurrentApi.Info("崩坏三公告获取" + ex.Message + " " + ex.StackTrace + "\n"); } } } if (item.InnerText.Contains("【★4圣痕】")) { string[] StigmataText = item.InnerText.Split('\n'); ret_Text += "池子内容:\n"; for (int i = 0; i < StigmataText.Length - 1; i++) { try { List <string> StigmataList = GetItem(StigmataText[1 + i]); foreach (var item2 in StigmataList) { ret_Text += $"{item2}\n"; JZStigmata.Add(item2); } } catch (Exception ex) { QMLog.CurrentApi.Info("崩坏三公告获取" + ex.Message + " " + ex.StackTrace + "\n"); } } } } } else if (count == 14) { foreach (var item in rootnode.ChildNodes) { if (item.InnerText.Contains("精准补给A为")) { //UPA var result = GetUpStaff(item.InnerText); if (result.Count == 2) { ret_Text += $"精准A UP:{result[0]} {result[1]}\n"; UPAWeapon = result[0]; UPAStigmata = result[1]; } } if (item.InnerText.Contains("精准补给B为")) { //UPB var result = GetUpStaff(item.InnerText); if (result.Count == 2) { ret_Text += $"精准B UP:{result[0]} {result[1]}\n"; UPBWeapon = result[0]; UPBStigmata = result[1]; } } if (item.InnerText.Contains("【★4武器】")) { string[] WeaponText = item.InnerText.Split('\n'); ret_Text += "池子内容:\n"; for (int i = 0; i < WeaponText.Length - 1; i++) { try { List <string> WeaponList = GetItem(WeaponText[1 + i]); foreach (var item2 in WeaponList) { ret_Text += $"{item2}\n"; JZWeapon.Add(item2); } } catch (Exception ex) { QMLog.CurrentApi.Info("崩坏三公告获取" + ex.Message + " " + ex.StackTrace + "\n"); } } } if (item.InnerText.Contains("【★4圣痕】")) { string[] StigmataText = item.InnerText.Split('\n'); ret_Text += "池子内容:\n"; for (int i = 0; i < StigmataText.Length - 1; i++) { try { List <string> StigmataList = GetItem(StigmataText[1 + i]); foreach (var item2 in StigmataList) { ret_Text += $"{item2}\n"; JZStigmata.Add(item2); } } catch (Exception ex) { QMLog.CurrentApi.Info("崩坏三公告获取" + ex.Message + " " + ex.StackTrace + "\n"); } } } } } } catch (Exception ex) { QMLog.CurrentApi.Info("崩坏三公告获取" + ex.Message + " " + ex.StackTrace + "\n"); } } else if (title.Contains("扩充")) { try { rootnode = htmlDoc.DocumentNode.SelectSingleNode($"/html[1]/body[1]/div[1]/div[2]/div[1]/div[2]/div[1]/div[1]/div[3]/div[2]"); var count = rootnode.ChildNodes.Count; string imgurl = ""; List <string> Uptime = new List <string>(); foreach (var item in rootnode.ChildNodes) { if (item.SelectSingleNode("img[1]") != null) { try { HttpWebClient.Get(item.SelectSingleNode("img[1]").GetAttributeValue("src", "")); imgurl = item.SelectSingleNode("img[1]").GetAttributeValue("src", ""); Uptime = GetUpDate(imgurl); for (int i = 0; i < Uptime.Count; i++) { Uptime[i] = Date2DateTtime(Uptime[i]).ToString(); } } catch { } } } //扩充项目 ret_Text += "扩充补给 UP:\n"; foreach (var item in GetUpStaff(title.Substring(0, title.IndexOf("扩充补给")))) { ret_Text += $"{item}\n"; KC.Add(item); } if (KC.Count <= 2) { var kuochong = rootnode.SelectSingleNode($"p[2]"); foreach (var item in GetUpStaff(kuochong.InnerText)) { if (!KC.Contains(item)) { ret_Text += $"{item}\n"; KC.Add(item); } } } ret_Text += "其他角色:\n"; int KCCount = 0; foreach (var item in res.data.item_list) { item.itemstring = item.itemstring.Replace(":", "·"); string path = Path.Combine($@"{MainSave.AppDirectory}\装备卡\角色卡\", $"{item.itemstring}.png"); if (File.Exists(path)) { ret_Text += $"{item.itemstring}\n"; KC.Add(item.itemstring); KCCount++; } else if (item.itemstring.Length >= 5) { //路径修正 string pathrepair = item.itemstring.Insert(item.itemstring.IndexOf("真红骑士") == -1 ? 3 : 4, "·"); path = Path.Combine($@"{MainSave.AppDirectory}\装备卡\角色卡\", $"{pathrepair}.png"); if (File.Exists(path)) { ret_Text += $"{pathrepair}\n"; KC.Add(pathrepair); KCCount++; } } if (KCCount == 3) { break; } } } catch (Exception ex) { QMLog.CurrentApi.Info("崩坏三公告获取" + ex.Message + " " + ex.StackTrace + "\n"); } } //目前只支持寻找一次 break; } } return(ret_Text); } catch (Exception exc) { QMLog.CurrentApi.Info("崩坏三公告获取" + exc.Message); return(null); } }
public void TestConcurrent() { Exception threadException = null; List<string> expectedText = new List<string>(new string[] { "" }); string newfileName = "Text_TestConcurrent" + SRandom.Next().ToString(); HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "text"); bool keepLooping = true; List<Thread> threads = new List<Thread>(); List<HttpWebClient> openConnections = new List<HttpWebClient>(); Shared<uint> loops = new Shared<uint>(0); for (int ctr = 0; ctr < 10; ctr++) threads.Add(new Thread(delegate() { try { while (keepLooping) { HttpWebClient threadHttpWebClient = new HttpWebClient(); lock (openConnections) openConnections.Add(threadHttpWebClient); try { LoginAsRoot(threadHttpWebClient); HttpResponseHandler threadWebResponse = threadHttpWebClient.Get( "http://localhost:" + WebServer.Port + "/" + newfileName); Assert.AreEqual(HttpStatusCode.OK, threadWebResponse.StatusCode, "Bad status code"); lock (expectedText) Assert.IsTrue(expectedText.Contains(threadWebResponse.AsString()), "Unexpected response"); lock (loops) loops.Value++; } finally { lock (openConnections) openConnections.Remove(threadHttpWebClient); } } } catch (Exception e) { threadException = e; } })); foreach (Thread thread in threads) thread.Start(); try { while (loops.Value < 4) { Thread.Sleep(25); if (null != threadException) throw threadException; } HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=WriteAll"); webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.CookieContainer = httpWebClient.CookieContainer; string text = "text written on thread"; byte[] toWrite = Encoding.UTF8.GetBytes(text); lock (expectedText) expectedText.Add(text); webRequest.ContentLength = toWrite.Length; // Write the request webRequest.GetRequestStream().Write(toWrite, 0, toWrite.Length); using (HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse()) Assert.AreEqual(HttpStatusCode.Accepted, httpWebResponse.StatusCode, "Bad status code"); uint targetLoops = loops.Value * 2; // Wait until all open web connections are complete before chainging the expected text List<HttpWebClient> openWebConnectionsToComplete; lock (openConnections) openWebConnectionsToComplete = new List<HttpWebClient>(openConnections); bool connectionPresent; do { Thread.Sleep(25); connectionPresent = false; foreach (HttpWebClient webClient in openWebConnectionsToComplete) lock (openConnections) if (openConnections.Contains(webClient)) connectionPresent = true; } while (connectionPresent); expectedText = new List<string>(new string[] { text }); while (loops.Value < targetLoops) { Thread.Sleep(25); if (null != threadException) throw threadException; } } finally { keepLooping = false; foreach (Thread thread in threads) thread.Join(); } }
public void TryRead(HttpWebClient httpWebClient, string directory, string filename, IUserLogoner userLogoner, HttpStatusCode expectedStatus) { string userName; if (null != userLogoner) { userLogoner.Login(httpWebClient, WebServer); userName = userLogoner.Name; } else { Logout(httpWebClient); userName = "******"; } HttpResponseHandler webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + directory + "/" + filename); Assert.AreEqual(expectedStatus, webResponse.StatusCode, "Bad status code for user: " + userName); }
/// <summary> /// 发送Http请求 /// </summary> /// <param name="url">请求Url</param> /// <param name="method">请求类型</param> /// <param name="parameters">参数集合</param> /// <returns></returns> private String Request(string url, RequestMethod method = RequestMethod.Get, params RequestOption[] parameters) { HttpWebClient httpWebClient = new HttpWebClient(); HttpWebResponseResult responseResult = null; #region 发起Http数据请求 switch (method) { case RequestMethod.Get: { #region //请求头和请求参数预处理 RequestHeaderExecuting(httpWebClient); parameters = RequestGetExecuting(parameters); #endregion #region //传递参数 foreach (var item in parameters) { httpWebClient.SetField(item.Name, (string)item.Value); } #endregion //发起请求 responseResult = httpWebClient.Get(url); } break; case RequestMethod.Post: { #region //请求头和请求参数预处理 RequestHeaderExecuting(httpWebClient); parameters = RequestPostExecuting(parameters); #endregion #region //判断当前POST是否为Multipart(即同时包含普通表单字段和文件表单字段) bool isMultipart = false; foreach (var item in parameters) { if (item.IsBinary) { isMultipart = true; break; } } #endregion #region //传递参数 if (isMultipart) { foreach (var item in parameters) { if (item.IsBinary) { httpWebClient.SetField(item.Name, (byte[])item.Value, String.Empty, String.Empty); } else { httpWebClient.SetField(item.Name, (string)item.Value, true); } } } else { foreach (var item in parameters) { httpWebClient.SetField(item.Name, (string)item.Value); } } #endregion //发起请求 responseResult = httpWebClient.Post(url); } break; } #endregion return responseResult.IsSuccess ? responseResult.ResponseText : String.Empty; }
public void TestSetPassword() { HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); HttpResponseHandler webResponse; string username = "******" + SRandom.Next(100000).ToString(); webResponse = httpWebClient.Post("http://localhost:" + WebServer.Port + "/Users/UserDB?Method=CreateUser", new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("displayName", username), new KeyValuePair<string, string>("password", "password"), new KeyValuePair<string, string>("assignSession", true.ToString())); Assert.AreEqual(HttpStatusCode.Created, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(username + " created", webResponse.AsString(), "Unexpected response"); // Verify that the current user is the newly-created user webResponse = httpWebClient.Get("http://localhost:" + WebServer.Port + "/Users/[name].user", new KeyValuePair<string, string>("Method", "GetName")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(username, webResponse.AsString(), "Unexpected response"); webResponse = httpWebClient.Post("http://localhost:" + WebServer.Port + "/Users/" + username + ".user?Method=SetPassword", new KeyValuePair<string, string>("OldPassword", "password"), new KeyValuePair<string, string>("NewPassword", "22password")); Assert.AreEqual(HttpStatusCode.Accepted, webResponse.StatusCode, "Wrong status code when calling SetPassword"); Assert.AreEqual("Password changed", webResponse.AsString(), "Wrong response text when changing the password"); Logout(httpWebClient); // Log in as root webResponse = httpWebClient.Post( "http://localhost:" + WebServer.Port + "/Users/UserDB?Method=Login", new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("password", "22password")); Assert.AreEqual(HttpStatusCode.Accepted, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(username + " logged in", webResponse.AsString(), "Unexpected response"); }
public void TestLargeTextFile() { string newfileName = "TestLargeTextFile" + SRandom.Next().ToString(); HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "text"); StringBuilder textBuilder = new StringBuilder(); for (int ctr = 0; ctr < 50; ctr++) textBuilder.AppendLine("bhvueribksrtbgiusrhgvuigviuosh ' ngilusnbgsnlibghsiougbbhsrliugbhiseuhgusehy aerjgpo\"azerhvgiuSBHgaehriughg9heroyghaesruhgazr78gu7ghauibgyr8a7fageryugfayiubga67hfbayuewgfyaewubfg6i7szrhgysudrgf678aq4btfaewr6ighaseiuyaer578ntgrgyohwe5iug7aer8graeyugfseyukbg6z87rhgiuseras5hgaer67thfegase5iugh7zrdhgzzre5ya7e4iughaeafaewrtfg7uaesy4gf67ae4hfb"); string text = textBuilder.ToString().Trim(); byte[] toWrite = Encoding.UTF8.GetBytes(text); for (int requestCtr = 0; requestCtr < 30; requestCtr++) { HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=WriteAll"); webRequest.KeepAlive = true; webRequest.UnsafeAuthenticatedConnectionSharing = true; webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.CookieContainer = httpWebClient.CookieContainer; webRequest.ContentLength = toWrite.Length; // Write the request webRequest.GetRequestStream().Write(toWrite, 0, toWrite.Length); using (HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse()) { Assert.AreEqual(HttpStatusCode.Accepted, httpWebResponse.StatusCode, "Bad status code"); } HttpResponseHandler webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/" + newfileName, new KeyValuePair<string, string>("Method", "ReadAll")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(text, webResponse.AsString(), "Unexpected value"); } /*[Test] public void TestLargeTextFileSentSlowly() { /* * History on this test * * When I developed using the Mono / Suse VM, for some reason, large text files would get corrupted when * saved through the browser. The problem went away after I downloaded the VM's system updates, so I * assume that the problem had nothing to do with ObjectCloud. This unit test can be safely deleted * after using Weco with large text files is known to work. * * */ /*Assert.Fail("This isn't failing yet"); string newfileName = "TestLargeTextFile" + SRandom.Next().ToString(); HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); HttpResponseHandler webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/", new KeyValuePair<string, string>("Method", "CreateFile"), new KeyValuePair<string, string>("FileName", newfileName), new KeyValuePair<string, string>("FileType", "text")); Assert.AreEqual(HttpStatusCode.Created, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(newfileName + " created as text", webResponse.AsString(), "Unexpected response"); StringBuilder textBuilder = new StringBuilder(); for (int ctr = 0; ctr < 50; ctr++) textBuilder.AppendLine("bhvueribksrtbgiusrhgvuigviuosh ' ngilusnbgsnlibghsiougbbhsrliugbhiseuhgusehy aerjgpo\"azerhvgiuSBHgaehriughg9heroyghaesruhgazr78gu7ghauibgyr8a7fageryugfayiubga67hfbayuewgfyaewubfg6i7szrhgysudrgf678aq4btfaewr6ighaseiuyaer578ntgrgyohwe5iug7aer8graeyugfseyukbg6z87rhgiuseras5hgaer67thfegase5iugh7zrdhgzzre5ya7e4iughaeafaewrtfg7uaesy4gf67ae4hfb"); string text = textBuilder.ToString().Trim(); byte[] toWrite = Encoding.UTF8.GetBytes(text); HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=WriteAll"); webRequest.KeepAlive = true; webRequest.UnsafeAuthenticatedConnectionSharing = true; webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.CookieContainer = httpWebClient.CookieContainer; webRequest.ContentLength = toWrite.Length; // Write the request /*for (int ctr = 0; ctr < toWrite.Length; ctr++) { webRequest.GetRequestStream().Write(toWrite, ctr, 1); Thread.Sleep(1); }*/ /*webRequest.GetRequestStream().Write(toWrite, 0, toWrite.Length / 2); //Thread.Sleep(2000); webRequest.GetRequestStream().Write(toWrite, toWrite.Length / 2, toWrite.Length / 2); using (HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse()) { Assert.AreEqual(HttpStatusCode.Accepted, httpWebResponse.StatusCode, "Bad status code"); } webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/" + newfileName, new KeyValuePair<string, string>("Method", "ReadAll")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(text, webResponse.AsString(), "Unexpected value"); }*/ }
public void TestViewTextFile() { string newfileName = "TestUseText" + SRandom.Next().ToString() + ".txt"; HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "text"); HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=WriteAll"); webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.CookieContainer = httpWebClient.CookieContainer; string text = "huriownuifeowb,tw89hu8ofryuovrbywoivujrz,fgersykghvyauofho9fnauwielo"; byte[] toWrite = Encoding.UTF8.GetBytes(text); webRequest.ContentLength = toWrite.Length; // Write the request webRequest.GetRequestStream().Write(toWrite, 0, toWrite.Length); using (HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse()) { Assert.AreEqual(HttpStatusCode.Accepted, httpWebResponse.StatusCode, "Bad status code"); } HttpResponseHandler webResponse = httpWebClient.Get("http://localhost:" + WebServer.Port + "/" + newfileName); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(text, webResponse.AsString(), "Unexpected value"); Assert.AreEqual("text/plain", webResponse.ContentType, "Unexpected content type"); }
public void TestNoIndexFile() { string newfileName = "TestNoIndexFile" + SRandom.Next().ToString(); HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "directory"); HttpResponseHandler webResponse = httpWebClient.Post( "http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=SetIndexFile"); Assert.AreEqual(HttpStatusCode.Accepted, webResponse.StatusCode, "Bad status code"); Assert.AreEqual("Index file disabled", webResponse.AsString(), "Unexpected response"); webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/" + newfileName, new KeyValuePair<string, string>("Method", "GetIndexFile")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual("No index file", webResponse.AsString(), "Unexpected response"); }
public void TestMimeType(string mimeType, string extension) { string newfileName = "TestMimeType" + SRandom.Next().ToString() + "." + extension; HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "text"); HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=WriteAll"); webRequest.CookieContainer = httpWebClient.CookieContainer; webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; string text = "nurw348nuo48h78t40oghw9phq 98fh587ghr7soiyo578whvntronvaeihrfbow45gn98owvs78zrgh78whgnv8ono8q7iehgrb8h78qofhfb78wehgnow8"; byte[] toWrite = Encoding.UTF8.GetBytes(text); webRequest.ContentLength = toWrite.Length; // Write the request webRequest.GetRequestStream().Write(toWrite, 0, toWrite.Length); using (HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse()) { Assert.AreEqual(HttpStatusCode.Accepted, httpWebResponse.StatusCode, "Bad status code"); } HttpResponseHandler webResponse = httpWebClient.Get("http://localhost:" + WebServer.Port + "/" + newfileName); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(text, webResponse.AsString(), "Unexpected value"); Assert.AreEqual(mimeType, webResponse.ContentType, "Unexpected content type"); }
public void TestWebComponent_COOKIE() { string newfileName = "TestWebComponent_COOKIE" + SRandom.Next().ToString(); HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "text"); HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=WriteAll"); webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.CookieContainer = httpWebClient.CookieContainer; string text = "inside the component"; byte[] toWrite = Encoding.UTF8.GetBytes(text); webRequest.ContentLength = toWrite.Length; // Write the request webRequest.GetRequestStream().Write(toWrite, 0, toWrite.Length); using (HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse()) { Assert.AreEqual(HttpStatusCode.Accepted, httpWebResponse.StatusCode, "Bad status code"); } string componentfileName = "TestWebComponentSanity" + SRandom.Next().ToString(); httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", componentfileName, "text"); webRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost:" + WebServer.Port + "/" + componentfileName + "?Method=WriteAll"); webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.CookieContainer = httpWebClient.CookieContainer; text = "xxx <? WebComponent($_COOKIE[\"Filename\"] . \"?Method=ReadAll\") ?> xxx"; toWrite = Encoding.UTF8.GetBytes(text); webRequest.ContentLength = toWrite.Length; // Write the request webRequest.GetRequestStream().Write(toWrite, 0, toWrite.Length); using (HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse()) { Assert.AreEqual(HttpStatusCode.Accepted, httpWebResponse.StatusCode, "Bad status code"); } Cookie cookie = new Cookie("Filename", newfileName); cookie.Domain = "localhost"; httpWebClient.CookieContainer.Add(cookie); HttpResponseHandler webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/" + componentfileName, new KeyValuePair<string, string>("Method", "ResolveComponents")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual("xxx inside the component xxx", webResponse.AsString(), "Unexpected value"); }
public void TestUseBinary() { string newfileName = "TestUseBinary" + SRandom.Next().ToString(); HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "binary"); HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=WriteAll"); webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.CookieContainer = httpWebClient.CookieContainer; byte[] binary = SRandom.NextBytes(2048); webRequest.ContentLength = binary.Length; // Write the request webRequest.GetRequestStream().Write(binary, 0, binary.Length); using (HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse()) { Assert.AreEqual(HttpStatusCode.Accepted, httpWebResponse.StatusCode, "Bad status code"); } HttpResponseHandler webResponse = httpWebClient.Get( "http://localhost:" + WebServer.Port + "/" + newfileName, new KeyValuePair<string, string>("Method", "ReadAll")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.IsTrue(Enumerable.Equals(binary, webResponse.AsBytes()), "Unexpected value"); }
public static ISongList GetPlatformSongList(MusicSource type, string url) { //url正则取id分析 ISongList result; try { if (type == MusicSource.Netease) { string id = new Regex("(?<=playlist\\?id=)[0-9]+").Match(url).Value; string requestUrl = "http://blog.ylz1.cn/page/music/api.php"; byte[] data = HttpWebClient.Post(requestUrl, Encoding.UTF8.GetBytes($"types=playlist&id={id}")); JObject jobj = JObject.Parse(Encoding.UTF8.GetString(data)); result = JsonConvert.DeserializeObject <NeteaseList>(jobj["playlist"].ToString()); //音乐写入 List <NeteaseMusic> musics = new List <NeteaseMusic>(); JArray playlist = JArray.Parse(jobj["playlist"]["tracks"].ToString()); foreach (var info in playlist) { //读取歌手数组 JArray ja = JArray.Parse(info["ar"].ToString()); List <string> artists = new List <string>(); foreach (var item in ja.Children()) { artists.Add(item["name"].ToString()); } //写入返回结果 musics.Add(new NeteaseMusic { Id = info["id"].ToString(), artist = artists.ToArray(), Name = info["name"].ToString(), Album = info["al"]["name"].ToString(), CoverId = info["al"]["pic_str"].ToString() }); } result.Musics = musics.ToArray(); } else if (type == MusicSource.Tencent) { //获取重定向location WebHeaderCollection whc = new WebHeaderCollection(); HttpWebClient.Get(url, "", ref whc, false); //获取location中的id string id = new Regex("(?<=id=)[0-9]+").Match(whc[HttpResponseHeader.Location]).Value; //发出请求 string requestUrl = $"https://api.qq.jsososo.com/songlist?id={id}"; byte[] data = HttpWebClient.Get(requestUrl); JObject jobj = JObject.Parse(Encoding.UTF8.GetString(data)); result = JsonConvert.DeserializeObject <TencentList>(jobj["data"].ToString()); //音乐写入 List <TencentMusic> musics = new List <TencentMusic>(); JArray playlist = JArray.Parse(jobj["data"]["songlist"].ToString()); foreach (var info in playlist) { musics.Add(JsonConvert.DeserializeObject <TencentMusic>(info.ToString())); } result.Musics = musics.ToArray(); } else { //获取歌单信息 HttpWebClient request = new HttpWebClient(); request.UserAgent = "Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.114 Mobile Safari/537.36"; request.AllowAutoRedirect = true; request.AutoCookieMerge = true; byte[] tmpData = request.DownloadData(new Uri(url)); string tmpR = new Regex("(?<=<script>)([\\s\\S]*?)(?=<\\/script>)").Match(Encoding.UTF8.GetString(tmpData).Replace(" ", "")).Value; string json = new Regex("(?<=phpParam=)([\\s\\S]*)(?=;)").Match(tmpR).Value; result = JsonConvert.DeserializeObject <KugouList>(json); //酷狗这歌单太乱了,需要多种方式实现 if (result is null) { //方式一 result = new KugouList { Id = Guid.NewGuid().ToString(), CoverUrl = "", Title = "酷狗歌单" }; //获取htmldata tmpData = HttpWebClient.Get(url); tmpR = new Regex("(?<=<script>)([\\s\\S]*?)(?=<\\/script>)").Match(Encoding.UTF8.GetString(tmpData).Replace(" ", "")).Value; json = new Regex("(?=\\[)([\\s\\S]*)(?<=\\])").Match(tmpR).Value; JArray playlist = JArray.Parse(json); //音乐写入 List <KugouMusic> musics = new List <KugouMusic>(); foreach (var info in playlist) { //写入返回结果 musics.Add(new KugouMusic { Id = info["hash"].ToString(), Artists = info["author_name"].ToString(), Name = info["song_name"].ToString(), //该项无法获取 Album = "" }); } result.Musics = musics.ToArray(); } else { //方式二 string reqUrl = $"http://m.kugou.com/plist/list/{result.Id}?json=true"; tmpData = HttpWebClient.Get(reqUrl); JToken jobj = JObject.Parse(Encoding.UTF8.GetString(tmpData))["list"]["list"]; int.TryParse(jobj["total"].ToString(), out int total); JArray playlist = JArray.Parse(jobj["info"].ToString()); List <KugouMusic> musics = new List <KugouMusic>(); foreach (var info in playlist) { string[] songName = info["filename"].ToString().Replace(" ", "").Split('-'); if (songName.Length != 2) { continue; } //写入返回结果 musics.Add(new KugouMusic { Id = info["hash"].ToString(), Artists = songName[0], Name = songName[1], Album = info["remark"].ToString() }); } //每一页只有30条,故循环获得 for (int i = 30; i < total; i += 30) { reqUrl = $"http://m.kugou.com/plist/list/{result.Id}?json=true&page={i / 30 + 1}"; tmpData = HttpWebClient.Get(reqUrl); jobj = JObject.Parse(Encoding.UTF8.GetString(tmpData))["list"]["list"]; playlist = JArray.Parse(jobj["info"].ToString()); foreach (var info in playlist) { string[] songName = info["filename"].ToString().Replace(" ", "").Split('-'); if (songName.Length != 2) { continue; } //写入返回结果 musics.Add(new KugouMusic { Id = info["hash"].ToString(), Artists = songName[0], Name = songName[1], Album = info["remark"].ToString() }); } } result.Musics = musics.ToArray(); } } } catch (Exception e) { throw e; } if (result is null) { throw new Exception(); } return(result); }
public void TestNewUser() { HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); HttpResponseHandler webResponse; string username = "******" + SRandom.Next(100000).ToString(); webResponse = httpWebClient.Post("http://localhost:" + WebServer.Port + "/Users/UserDB?Method=CreateUser", new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("displayName", username), new KeyValuePair<string, string>("password", "password"), new KeyValuePair<string, string>("assignSession", true.ToString())); Assert.AreEqual(HttpStatusCode.Created, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(username + " created", webResponse.AsString(), "Unexpected response"); // Verify that the current user is the newly-created user webResponse = httpWebClient.Get("http://localhost:" + WebServer.Port + "/Users/[name].user", new KeyValuePair<string, string>("Method", "GetName")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(username, webResponse.AsString(), "Unexpected response"); }