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"); }
public void TestCreateEmbeddedDatabase() { string newfileName = "TestCreateEmbeddedDatabase" + SRandom.Next().ToString() + ".db"; HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "database"); HttpResponseHandler webResponse = httpWebClient.Post( "http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=PostQuery", new KeyValuePair<string, string>("query", "create table testtable (testcol int)")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); int[] resultInts = webResponse.AsJsonReader().Deserialize<int[]>(); Assert.IsNotNull(resultInts, "Result deserialized as null"); Assert.AreEqual(0, resultInts[0], "Incorrect result"); webResponse = httpWebClient.Post( "http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=PostQuery", new KeyValuePair<string, string>("query", "insert into testtable (testcol) values (123);insert into testtable (testcol) values (456)")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); resultInts = webResponse.AsJsonReader().Deserialize<int[]>(); Assert.AreEqual(2, resultInts[0], "Incorrect result"); webResponse = httpWebClient.Post( "http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=PostQuery", new KeyValuePair<string, string>("query", "select * from testtable; select * from testtable")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Dictionary<string, object>[][] resultObjss = webResponse.AsJsonReader().Deserialize<Dictionary<string, object>[][]>(); Assert.AreEqual(2, resultObjss.Length, "Wrong number of queries returned"); foreach (Dictionary<string, object>[] resultObjs in resultObjss) { List<int> expected = new List<int>(new int[] {123,456}); foreach(Dictionary<string, object> resultObj in resultObjs) { int value = Convert.ToInt32(resultObj["testcol"]); Assert.IsTrue(expected.Contains(value), "Unexpected value: " + value); expected.Remove(value); } Assert.IsTrue(0 == expected.Count, "Expected values not returned: " + StringGenerator.GenerateCommaSeperatedList(expected)); } }
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 static string Record(string msg) { if (!IsOpen()) { return("未开启!"); } string host = StrongString.GetRight(msg.Replace(" ", ""), "查询备案"); if (!IsDomain(host)) { return("查询失败,不是域名!"); } byte[] data = HttpWebClient.Post("http://whois.chinaz.com/ylz1.cn", Encoding.UTF8.GetBytes($"DomainName={host}&ws=&isforceupdate=")); string str = Encoding.UTF8.GetString(data); string regTrade = StrongString.Between(str, "注册商</div><div class=\"fr WhLeList-right\"><div class=\"block ball\"><span>", "</span>"); if (str.Contains("未被注册或被隐藏") || str.Contains("站长工具暂不支持") || regTrade.Length > 200) { return("该域名未被注册或被隐藏!"); } //string contact = StrongString.Between(str, "联系人</div><div class=\"fr WhLeList-right block ball lh24\"><span>", "</span>"); //string email = StrongString.Between(str, "联系邮箱</div><div class=\"fr WhLeList-right block ball lh24\"><span>", "</span>"); string createDate = StrongString.Between(str, "创建时间</div><div class=\"fr WhLeList-right\"><span>", "</span>"); string deadline = StrongString.Between(str, "过期时间</div><div class=\"fr WhLeList-right\"><span>", "</span>"); string state = StrongString.Between(str, "状态</div><div class=\"fr WhLeList-right clearfix\"><p class=\"lh30 pr tip-sh\"><span>", "("); string dns = StrongString.Between(str, "DNS</div><div class=\"fr WhLeList-right\">", "</div>").Replace("<br/>", "、"); //return $"域名:{host}\n注册商:{regTrade}\n联系人:{contact}\n联系邮箱:{email}\n创建时间:{createDate}\n到期时间:{deadline}\n状态:{state}\ndns:{dns}"; return($"域名:{host}\n注册商:{regTrade}\n创建时间:{createDate}\n到期时间:{deadline}\n状态:{state}\ndns:{dns}"); }
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 SetFilePermission(HttpWebClient httpWebClient, string directory, string filename, string username, FilePermissionEnum filePermission) { HttpResponseHandler webResponse = httpWebClient.Post( "http://localhost:" + WebServer.Port + directory + "?Method=SetFilePermission", new KeyValuePair<string, string>("FileName", filename), new KeyValuePair<string, string>("UserOrGroup", username), new KeyValuePair<string, string>("FilePermission", filePermission.ToString())); Assert.AreEqual(HttpStatusCode.Accepted, webResponse.StatusCode, "Bad status code"); Assert.AreEqual("Permission set to " + filePermission.ToString(), webResponse.AsString(), "Unexpected response"); }
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); }
public OpenIDLogonerThroughObjectCloud(string name, string password, IWebServer webServer, IWebServer secondWebServer) : this(name, password, secondWebServer) { HttpWebClient httpWebClient = new HttpWebClient(); WebServerTestBase.LoginAsRoot(httpWebClient, webServer); HttpResponseHandler webResponse = httpWebClient.Post( "http://localhost:" + webServer.Port + "/?Method=CreateFile", new KeyValuePair<string, string>("FileName", name), new KeyValuePair<string, string>("FileType", "directory")); Assert.AreEqual(HttpStatusCode.Created, webResponse.StatusCode, "Bad status code"); webResponse = httpWebClient.Post( "http://localhost:" + webServer.Port + "/?Method=SetFilePermission", new KeyValuePair<string, string>("FileName", name), new KeyValuePair<string, string>("UserOrGroup", Name), new KeyValuePair<string, string>("FilePermission", FilePermissionEnum.Administer.ToString())); Assert.AreEqual(HttpStatusCode.Accepted, webResponse.StatusCode, "Bad status code"); _WritableDirectory = "/" + _Name + "/"; }
//进行OCR public OCR_Result TXOCR() { string image = HttpTool.UrlEncode(Convert.ToBase64String(File.ReadAllBytes($"{CQSave.ImageDirectory}\\ocrtemp.jpg"))).Replace("%3d", "%3D").Replace("%2f", "%2F").Replace("%2b", "%2B"); string app_id = "2123406403"; string app_key = "KtGhR0iLzgWbdykj"; string timestamp = GetTimeStamp().ToString(); Random rd = new Random(); string noicestr = rd.Next().ToString(); string sign = $"app_id={app_id}&image={image}&nonce_str={noicestr}&time_stamp={timestamp}&app_key={app_key}"; sign = GetMD5(sign).ToUpper(); string url = $"https://api.ai.qq.com/fcgi-bin/ocr/ocr_generalocr"; string data = $"app_id={app_id}&image={image}&nonce_str={noicestr}&time_stamp={timestamp}&sign={sign}"; byte[] by = Encoding.UTF8.GetBytes(data); by = HttpWebClient.Post(url, by); string result = Encoding.UTF8.GetString(by); //richTextBox1.Text = result; return(JsonConvert.DeserializeObject <OCR_Result>(result)); }
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 void Post() { HttpWebServer aHttpListener = new HttpWebServer("http://127.0.0.1:8094/"); try { object aLock = new object(); string aReceivedRequest = null; aHttpListener.StartListening(x => { if (x.Request.HttpMethod == "POST") { lock (aLock) { aReceivedRequest = x.GetRequestMessageStr(); } x.SendResponseMessage("blabla"); } else { x.Response.StatusCode = 404; } }); HttpWebResponse aWebResponse = HttpWebClient.Post(new Uri("http://127.0.0.1:8094/hello/"), "abcd"); Assert.AreEqual(HttpStatusCode.OK, aWebResponse.StatusCode); string aResponseMessage = aWebResponse.GetResponseMessageStr(); Assert.AreEqual("abcd", aReceivedRequest); Assert.AreEqual("blabla", aResponseMessage); } finally { aHttpListener.StopListening(); } }
public static void LoginAsRoot(HttpWebClient httpWebClient, IWebServer webServer) { // Log in as root HttpResponseHandler webResponse = httpWebClient.Post( "http://localhost:" + webServer.Port + "/Users/UserDB?Method=Login", new KeyValuePair<string, string>("username", "root"), new KeyValuePair<string, string>("password", "root")); Assert.AreEqual(HttpStatusCode.Accepted, webResponse.StatusCode, "Bad status code"); Assert.AreEqual("root logged in", webResponse.AsString(), "Unexpected response"); }
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 Login(HttpWebClient httpWebClient, IWebServer webServer) { HttpResponseHandler webResponse = httpWebClient.Post( "http://localhost:" + webServer.Port + "/Users/UserDB?Method=Login", new KeyValuePair<string, string>("username", UserName), new KeyValuePair<string, string>("password", Password)); Assert.AreEqual(HttpStatusCode.Accepted, webResponse.StatusCode, "Bad status code"); }
public void TestCreateFileConcurrent() { string newfileName = "CreateFile_TestCreateFileConcurrent" + SRandom.Next().ToString(); Shared<uint> numSuccess = new Shared<uint>(0); Shared<uint> numConflict = new Shared<uint>(0); List<Thread> threads = new List<Thread>(); Exception threadException = null; DateTime startTime = DateTime.Now.AddMilliseconds(100); for (int ctr = 0; ctr < 10; ctr++) threads.Add(new Thread(delegate() { while (DateTime.Now < startTime) { } // spin until it's time to start try { HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); HttpResponseHandler webResponse = httpWebClient.Post( "http://localhost:" + WebServer.Port + "/?Method=CreateFile", new KeyValuePair<string, string>("FileName", newfileName), new KeyValuePair<string, string>("FileType", "text")); switch (webResponse.StatusCode) { case HttpStatusCode.Created: lock (numSuccess) numSuccess.Value++; break; case HttpStatusCode.Conflict: lock (numConflict) numConflict.Value++; break; default: Assert.Fail("Unexpected status when creating duplicate files"); break; } } catch (Exception e) { threadException = e; } })); foreach (Thread thread in threads) thread.Start(); foreach (Thread thread in threads) thread.Join(); if (null != threadException) throw threadException; Assert.AreEqual(1, numSuccess.Value, "Wrong number of successfully created files"); Assert.AreEqual(threads.Count - 1, numConflict.Value, "Wrong number of conflicts"); }
public void TestIndexFile() { string newfileName = "TestIndexFile" + SRandom.Next().ToString(); HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "directory"); CreateFile(WebServer, httpWebClient, "/" + newfileName, "text.txt", "text"); HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost:" + WebServer.Port + "/" + newfileName + "/text.txt?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.Post( "http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=SetIndexFile", new KeyValuePair<string, string>("IndexFile", "text.txt")); Assert.AreEqual(HttpStatusCode.Accepted, webResponse.StatusCode, "Bad status code"); Assert.AreEqual("Index file is now: " + "text.txt", webResponse.AsString(), "Unexpected response"); 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 TestStoredProcedurePermissions() { string newfileName = "TestStoredProcedurePermissions" + SRandom.Next().ToString() + ".db"; HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "database"); HttpResponseHandler webResponse = httpWebClient.Post( "http://*****:*****@testcol)"; storedProc["MinimumPermission"] = "Administer"; webResponse = httpWebClient.Post( "http://*****:*****@testcol", "The value")); Assert.AreEqual(HttpStatusCode.Unauthorized, webResponse.StatusCode, "Bad status code"); LoginAsRoot(httpWebClient); webResponse = httpWebClient.Post( "http://*****:*****@testcol", "The value")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); }
public void TestCanDeleteGroup() { 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"); webResponse = httpWebClient.Post("http://localhost:" + WebServer.Port + "/Users/UserDB?Method=DeleteGroup", new KeyValuePair<string, string>("groupname", groupname)); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(groupname + " deleted", webResponse.AsString(), "Unexpected response"); }
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"); }
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 Login(HttpWebClient httpWebClient, IWebServer webServer) { HttpResponseHandler webResponse = httpWebClient.Post( "http://localhost:" + webServer.Port + "/Users/UserDB?Method=OpenIDLogin", new KeyValuePair<string, string>("openid_url", Name)); // The returned page should just have a "Submit" button in order to continue OpenID Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Uri responseUri = webResponse.HttpWebResponse.ResponseUri; RequestParameters openIdGetParameters = new RequestParameters(responseUri.Query.Substring(1)); Dictionary<string, string> formArgs = new Dictionary<string, string>(openIdGetParameters); formArgs["password"] = Password; formArgs.Remove("Method"); webResponse = httpWebClient.Post( "http://localhost:" + SecondWebServer.Port + "/Users/UserDB?Method=ProvideOpenID", formArgs); Assert.AreEqual(HttpStatusCode.Accepted, webResponse.StatusCode); }
public void CreateFile(IWebServer webServer, HttpWebClient httpWebClient, string directory, string filename, string typeid, HttpStatusCode expectedStatusCode) { HttpResponseHandler webResponse = httpWebClient.Post( "http://localhost:" + webServer.Port + directory + "?Method=CreateFile", new KeyValuePair<string, string>("FileName", filename), new KeyValuePair<string, string>("FileType", typeid)); Assert.AreEqual(expectedStatusCode, webResponse.StatusCode, "Bad status code"); // Read the response so the server isn't left trying to transmit webResponse.AsBytes(); }
public void Logout(HttpWebClient httpWebClient) { HttpResponseHandler webResponse = httpWebClient.Post( "http://localhost:" + WebServer.Port + "/Users/UserDB?Method=Logout"); Assert.AreEqual(HttpStatusCode.Accepted, webResponse.StatusCode, "Bad status code"); Assert.AreEqual("logged out", webResponse.AsString(), "Unexpected response"); }
public void TestStoredProcedure() { string newfileName = "TestStoredProcedure" + SRandom.Next().ToString() + ".db"; HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "database"); HttpResponseHandler webResponse = httpWebClient.Post( "http://*****:*****@testcol)"; webResponse = httpWebClient.Post( "http://*****:*****@testcol", "The value")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); int[] resultInts = webResponse.AsJsonReader().Deserialize<int[]>(); Assert.AreEqual(1, resultInts[0], "Incorrect result"); webResponse = httpWebClient.Post( "http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=PostQuery", new KeyValuePair<string, string>("query", "select testcol from testtable")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Dictionary<string, object>[][] resultObj = webResponse.AsJsonReader().Deserialize<Dictionary<string, object>[][]>(); Assert.AreEqual("The value", resultObj[0][0]["testcol"], "Value stored incorrectly"); }
public void TestParameters() { string newfileName = "TestParameters" + SRandom.Next().ToString() + ".db"; HttpWebClient httpWebClient = new HttpWebClient(); LoginAsRoot(httpWebClient); CreateFile(WebServer, httpWebClient, "/", newfileName, "database"); HttpResponseHandler webResponse = httpWebClient.Post( "http://*****:*****@val=345", new KeyValuePair<string, string>("query", "insert into testtable (testcol) values (@val)"), new KeyValuePair<string, string>("@val", "789")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); resultInts = webResponse.AsJsonReader().Deserialize<int[]>(); Assert.AreEqual(1, resultInts[0], "Incorrect result"); webResponse = httpWebClient.Post( "http://localhost:" + WebServer.Port + "/" + newfileName + "?Method=PostQuery", new KeyValuePair<string, string>("query", "select testcol from testtable")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Dictionary<string, object>[][] resultObj = webResponse.AsJsonReader().Deserialize<Dictionary<string, object>[][]>(); Assert.IsFalse((object)345 == resultObj[0][0]["testcol"], "GET parameter overrulled POST parameter"); Assert.AreEqual(789, resultObj[0][0]["testcol"], "POST parameter stored incorrectly"); }
public void TestWebComponent_REQUEST() { string newfileName = "TestWebComponent_REQUEST" + 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($_REQUEST[\"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"); cookie.Value = ""; webResponse = httpWebClient.Post( "http://localhost:" + WebServer.Port + "/" + componentfileName + "?Method=ResolveComponents", new KeyValuePair<string, string>("Filename", newfileName)); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual("xxx inside the component xxx", webResponse.AsString(), "Unexpected value"); webResponse = httpWebClient.Post( "http://localhost:" + WebServer.Port + "/" + componentfileName + "?Method=ResolveComponents&Filename=" + newfileName, new KeyValuePair<string, string>("Filename", "xyz")); Assert.AreEqual(HttpStatusCode.OK, webResponse.StatusCode, "Bad status code"); Assert.AreEqual("xxx inside the component xxx", webResponse.AsString(), "Unexpected value"); }
/// <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 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 Login(HttpWebClient httpWebClient, string username, string password, int port) { // Log in as root HttpResponseHandler webResponse = httpWebClient.Post( "http://localhost:" + port + "/Users/UserDB?Method=Login", new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("password", password)); Assert.AreEqual(HttpStatusCode.Accepted, webResponse.StatusCode, "Bad status code"); Assert.AreEqual(username + " logged in", webResponse.AsString(), "Unexpected response"); }