private void Button_Click(object sender, RoutedEventArgs e) { HttpRequest CheckToken = new HttpRequest(); CheckToken.AddUrlParam("access_token", Properties.Settings.Default.AccessToken); CheckToken.AddUrlParam("v", "5.63"); string Result = CheckToken.Get("https://api.vk.com/method/account.setOffline").ToString(); Dictionary <string, string> Dict = new Dictionary <string, string>(); try { Dict = JsonConvert.DeserializeObject <Dictionary <string, string> >(Result); } catch { Dict.Add("response", "0"); } if (Dict["response"] != "1") { AuthForm GetToken = new AuthForm(); GetToken.ShowDialog(); } Maiven open = new Maiven(); open.Show(); this.Close(); }
public User GetUser(string id) //Получение заданной информации о пользователе с заданным ID { if (Data.Users.Find(x => x.id == id) != null) { return(null); } HttpRequest GetInformation = new HttpRequest(); //GetInformation.AddUrlParam("user_ids", UserId); GetInformation.AddUrlParam("access_token", _Token); //string Params = ""; //foreach (string i in Fields) //{ // Params += i + ","; //} //Params = Params.Remove(Params.Length - 1); //GetInformation.AddUrlParam("fields", Params); GetInformation.AddUrlParam("user", id); GetInformation.AddUrlParam("v", "5.95"); string Result = GetInformation.Get(__VKAPIURL + "execute.GetUserById").ToString(); //Result = Result.Substring(13, Result.Length - 15); //Dictionary<string, string> Dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(Result); return(new User(Result)); }
public List <string> GetAudioInformation(string UserId, string[] Fields) { List <string> traks = new List <string>(); HttpRequest GetInformation = new HttpRequest(); GetInformation.AddUrlParam("user_id", UserId); GetInformation.AddUrlParam("access_token", _Token); GetInformation.AddUrlParam("v", "5.103"); string Result = GetInformation.Get(__VKAPIURL + "audio.get").ToString(); string Count = "{" + Result.Substring(Result.IndexOf("\"count\":"), Result.IndexOf(",\"items\"") - Result.IndexOf("\"count\":")) + "}"; Dictionary <string, string> audioCount = JsonConvert.DeserializeObject <Dictionary <string, string> >(Count); Result = Result.Substring(35, Result.Length - 38); string[] stringSeparators = new string[] { "{\"artist\"" }; string[] subResults = Result.Split(stringSeparators, StringSplitOptions.None); for (int i = 1; i < subResults.Length; i++) { subResults[i] = "{\"artist\"" + subResults[i].Substring(0, subResults[i].IndexOf(",\"duration\"")) + "}"; Dictionary <string, string> Dict = JsonConvert.DeserializeObject <Dictionary <string, string> >(subResults[i]); traks.Add(i.ToString() + ". " + Dict["artist"] + " - " + Dict["title"]); } //traks.Sort(); traks.Add("Count: " + (short.Parse(audioCount["count"]) - 1).ToString()); return(traks); }
public HttpRequest CreateHttpRequest(string cabID, string APIV, string accessToken) { HttpRequest Request = new HttpRequest(); Request.AddUrlParam("account_id", cabID); Request.AddUrlParam("access_token", accessToken); Request.AddUrlParam("v", APIV); return(Request); }
public string GetMethod(string name, string[] arg, string tokens) { HttpRequest GetCityById = new HttpRequest(); foreach (var tmp in arg) { GetCityById.AddUrlParam(tmp.Split('=')[0], tmp.Split('=')[1]); } GetCityById.AddUrlParam("access_token", tokens); GetCityById.AddUrlParam("v", "5.74"); return(GetCityById.Get("https://api.vk.com/method/" + name).ToString()); }
public string GetCountryById(string CountryId) //Перевод ID страны в название { HttpRequest GetCountryById = new HttpRequest(); GetCountryById.AddUrlParam("country_ids", CountryId); GetCountryById.AddUrlParam("access_token", _Token); string Result = GetCountryById.Get(__VKAPIURL + "database.getCountriesById").ToString(); Result = Result.Substring(13, Result.Length - 15); Dictionary <string, string> Dict = JsonConvert.DeserializeObject <Dictionary <string, string> >(Result); return(Dict["name"]); }
public string GetCityById(string CityId) //Перевод ID города в название { HttpRequest GetCityById = new HttpRequest(); GetCityById.AddUrlParam("city_ids", CityId); GetCityById.AddUrlParam("access_token", Token); GetCityById.AddUrlParam("version", "5.52"); string Result = GetCityById.Get(VKAPIURL + "database.getCitiesById").ToString(); Result = Result.Substring(13, Result.Length - 15); Dictionary <string, string> Dict = JsonConvert.DeserializeObject <Dictionary <string, string> >(Result); return(Dict["name"]); }
/// <summary> /// Создаёт рекламную кампанию. /// </summary> /// <returns></returns> public CreateCampaingResponse CreateCampaign(CreateCampaignData[] Cdata) { string data; HttpRequest Request = new HttpRequest(); Request.AddUrlParam("account_id", _CABID); data = JsonConvert.SerializeObject(Cdata); Request.AddUrlParam("data", data); Request.AddUrlParam("access_token", _Token); Request.AddUrlParam("v", __API_VERSION); string json = Request.Get(__VKAPIURL + "ads.createCampaigns").ToString(); CreateCampaingResponse campaings = JsonConvert.DeserializeObject <CreateCampaingResponse>(json); return(campaings); }
public Dictionary <string, string> GetID() //Получение заданной информации о пользователе с заданным ID { HttpRequest GetID = new HttpRequest(); //GetID.AddUrlParam("user_ids", UserId); GetID.AddUrlParam("access_token", Token); GetID.AddUrlParam("version", "5.73"); string Result = GetID.Get(__VKAPIURL + "users.get").ToString(); Result = Result.Substring(13, Result.Length - 15); Dictionary <string, string> Dict = JsonConvert.DeserializeObject <Dictionary <string, string> >(Result); return(Dict); }
public string GetUserInformation(string UserId, string[] Fields) { string Username = ""; HttpRequest GetInformation = new HttpRequest(); GetInformation.AddUrlParam("user_id", UserId); GetInformation.AddUrlParam("access_token", _Token); GetInformation.AddUrlParam("v", "5.103"); string Result = GetInformation.Get(__VKAPIURL + "users.get").ToString(); Result = Result.Substring(13, Result.Length - 15); Dictionary <string, string> Dict = JsonConvert.DeserializeObject <Dictionary <string, string> >(Result); Username = Dict["first_name"] + " " + Dict["last_name"]; return(Username); }
/// <summary> /// Возвращает ссылку на фото, имя, фамилию. /// </summary> /// <returns></returns> public Dictionary <string, string> GetUserInfo() { Dictionary <string, string> Dict = new Dictionary <string, string>(); HttpRequest GetUserInfo = new HttpRequest(); GetUserInfo.AddUrlParam("user_ids", Properties.Settings.Default.UserID); string Params = "photo_100,first_name,last_name,"; GetUserInfo.AddUrlParam("fields", Params); GetUserInfo.AddUrlParam("access_token", _Token); GetUserInfo.AddUrlParam("v", __API_VERSION); string Result = GetUserInfo.Get(__VKAPIURL + "users.get").ToString(); Result = Result.Substring(13, Result.Length - 15); Dict = JsonConvert.DeserializeObject <Dictionary <string, string> >(Result); return(Dict); }
/// <summary> /// Получает баланс кабинета. /// </summary> /// <returns></returns> public string GetBudget() { string Budget = "Доступно только владельцу"; Dictionary <string, string> SBudget = new Dictionary <string, string>(); HttpRequest GetBudget = new HttpRequest(); GetBudget.AddUrlParam("account_id", _CABID); GetBudget.AddUrlParam("access_token", _Token); GetBudget.AddUrlParam("v", __API_VERSION); string Result = GetBudget.Get(__VKAPIURL + "ads.getBudget").ToString(); System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); if (Result.Contains("response")) { SBudget = JsonConvert.DeserializeObject <Dictionary <string, string> >(Result); Budget = SBudget["response"]; } return(Budget); }
public Dictionary <string, string> GetInformation(string UserId, string[] Fields) //Получение заданной информации о пользователе с заданным ID { HttpRequest GetInformation = new HttpRequest(); GetInformation.AddUrlParam("user_ids", UserId); GetInformation.AddUrlParam("access_token", _Token); string Params = ""; foreach (string i in Fields) { Params += i + ","; } Params = Params.Remove(Params.Length - 1); GetInformation.AddUrlParam("fields", Params); string Result = GetInformation.Get(__VKAPIURL + "users.get").ToString(); Result = Result.Substring(13, Result.Length - 15); Dictionary <string, string> Dict = JsonConvert.DeserializeObject <Dictionary <string, string> >(Result); return(Dict); }
/// <summary> /// Получение заданной информации о пользователе с заданным ID. /// </summary> /// <param name="UserId"> Id пользователя. </param> /// <param name="Fields"></param> /// <returns></returns> public Dictionary <string, string> GetInformation(string UserId, string[] Fields) { HttpRequest GetInformation = new HttpRequest(); GetInformation.AddUrlParam("user_ids", UserId); GetInformation.AddUrlParam("access_token", Token); GetInformation.AddUrlParam("version", "5.52"); string Params = ""; foreach (string i in Fields) { Params += i + ","; } Params = Params.Remove(Params.Length - 1); GetInformation.AddUrlParam("fields", Params); string Result = GetInformation.Get(VKAPIURL + "users.get").ToString(); Result = Result.Substring(13, Result.Length - 15); Dictionary <string, string> Dict = JsonConvert.DeserializeObject <Dictionary <string, string> >(Result); return(Dict); }
public List <String> GetFriends(string id) { List <String> Friends = new List <string>(); int count; HttpRequest GetInformation = new HttpRequest(); //GetInformation.AddUrlParam("user_ids", UserId); GetInformation.AddUrlParam("access_token", _Token); //string Params = ""; //foreach (string i in Fields) //{ // Params += i + ","; //} //Params = Params.Remove(Params.Length - 1); //GetInformation.AddUrlParam("fields", Params); GetInformation.AddUrlParam("user", id); GetInformation.AddUrlParam("v", "5.95"); string Result = GetInformation.Get(__VKAPIURL + "execute.GetUsersFriends").ToString(); if (Result == null || Result.IndexOf("error") > 0) { return(Friends); } if (Result.IndexOf("count") > 0) { count = int.Parse(Result.Split(':')[2].Split(',')[0]); Result = Result.Split(':')[3].Split('[')[1].Split(']')[0]; if (count > 0) { Friends.AddRange(Result.Split(',')); } } return(Friends); }
public static dynamic docs_save(string path_file, string name_doc = "Unknown", string v = "5.21") { Dictionary<string, dynamic> result; string error = ""; var request = new HttpRequest(); request.AddUrlParam("access_token", Settings1.Default.token); request.AddUrlParam("v", v); try { string content = request.Get(uri_api + "docs.getUploadServer").ToString(); result = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(content); string url_upload = result["response"]["upload_url"]; request = new HttpRequest(); request.AddFile("file", path_file); content = request.Post(url_upload).ToString(); result = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(content); request = new HttpRequest(); request.AddUrlParam("file", result["file"]); request.AddUrlParam("title", name_doc.Replace(".jpg", "")); request.AddUrlParam("access_token", Settings1.Default.token); request.AddUrlParam("v", v); content = request.Get(uri_api + "docs.save").ToString(); result = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(content); string result_string = "doc" + result["response"][0]["owner_id"] + "_" + result["response"][0]["id"]; return result_string; } catch (Exception ex) { MessageBox.Show(error = ex.Message + " " + ex.InnerException); return null; } }
public List <String> GetGroups(string id) { List <String> Groups = new List <string>(); //int count; HttpRequest GetInformation = new HttpRequest(); //GetInformation.AddUrlParam("user_ids", UserId); GetInformation.AddUrlParam("access_token", _Token); //string Params = ""; //foreach (string i in Fields) //{ // Params += i + ","; //} //Params = Params.Remove(Params.Length - 1); //GetInformation.AddUrlParam("fields", Params); GetInformation.AddUrlParam("user", id); GetInformation.AddUrlParam("v", "5.95"); string Result = GetInformation.Get(__VKAPIURL + "execute.GetGroups").ToString(); if (Result == null || Result.IndexOf("error") > 0) { return(Groups); } else { if (Result.Length > 0) { Groups.AddRange(Result.Split('[')[1].Split(']')[0].Split(',')); } Groups.RemoveAll(x => x.Length == 0); } return(Groups); }
public HttpResponse Get(string action, string authorizationToken, params KeyValuePair <string, string>[] queryParams) { using (var request = new HttpRequest(baseUri)) { request.AddHeader("Authorization", authorizationToken); request.IgnoreProtocolErrors = true; foreach (var param in queryParams) { request.AddUrlParam(param.Key, param.Value); } request.Get(action).ToString(); return(request.Response); } }
public static dynamic friends_get(string id_user, string fields = "screen_name, photo_max_orig") { Dictionary<string, dynamic> result; string error; var request = new HttpRequest(); request.AddUrlParam("user_ids", id_user); request.AddUrlParam("order", "hints"); request.AddUrlParam("fields", fields); request.AddUrlParam("access_token", Settings1.Default.token); try { string content = request.Get(uri_api + "friends.get").ToString(); result = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(content); return result["response"]; } catch (Exception ex) { MessageBox.Show(error = ex.Message + " " + ex.InnerException); return null; } }
public static dynamic messages_history(string id_user, string v="5.21") { Dictionary<string, dynamic> result; string error = ""; var request = new HttpRequest(); request.AddUrlParam("user_id", id_user); request.AddUrlParam("access_token", Settings1.Default.token); request.AddUrlParam("v", v); try { string content = request.Get(uri_api + "messages.getHistory").ToString(); result = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(content); return result["response"]; } catch (Exception ex) { MessageBox.Show(error = ex.Message + " " + ex.InnerException); return null; } }
/// <inheritdoc /> public override void Process(BotData data) { base.Process(data); #region Request // Set base URL var localUrl = ReplaceValues(url, data); var cType = ReplaceValues(contentType, data); var oldJar = data.Cookies; // Create request HttpRequest request = new HttpRequest(); // Setup options var timeout = data.GlobalSettings.General.RequestTimeout * 1000; request.IgnoreProtocolErrors = true; request.AllowAutoRedirect = autoRedirect; request.EnableEncodingContent = acceptEncoding; request.ReadWriteTimeout = timeout; request.ConnectTimeout = timeout; request.KeepAlive = true; request.MaximumAutomaticRedirections = data.ConfigSettings.MaxRedirects; // Check if it has GET parameters if (ParseQuery && localUrl.Contains('?') && localUrl.Contains('=')) { // Remove the query from the base URL localUrl = ReplaceValues(url.Split('?')[0], data); data.Log(new LogEntry($"Calling Base URL: {localUrl}", Colors.MediumTurquoise)); // Parse the GET parameters var getParams = ReplaceValues(url.Split('?')[1], data); var paramList = getParams.Split('&'); // Build the query, first replace variables in them and encode the parameters foreach (var par in paramList) { var split = par.Split('='); // Encode them if needed if (split[0].Contains('%')) { split[0] = Uri.EscapeDataString(split[0]); } if (split[1].Contains('%')) { split[1] = Uri.EscapeDataString(split[1]); } // Add them to the query request.AddUrlParam(split[0], split[1]); data.Log(new LogEntry($"Added Query Parameter: {split[0]} = {split[1]}", Colors.MediumTurquoise)); } } else { data.Log(new LogEntry($"Calling URL: {localUrl}", Colors.MediumTurquoise)); } // Set up the Content and Content-Type HttpContent content = null; switch (requestType) { case RequestType.Standard: var pData = ReplaceValues(Regex.Replace(postData, @"(?<!\\)\\n", Environment.NewLine).Replace(@"\\n", @"\n"), data); if (CanContainBody(method)) { if (encodeContent) { // Very dirty but it works var nonce = data.Random.Next(1000000, 9999999); pData = pData.Replace("&", $"{nonce}&{nonce}").Replace("=", $"{nonce}={nonce}"); pData = string.Join("", BlockFunction.SplitInChunks(pData, 2080) .Select(s => Uri.EscapeDataString(s))) .Replace($"{nonce}%26{nonce}", "&").Replace($"{nonce}%3D{nonce}", "="); } content = new StringContent(pData); content.ContentType = cType; data.Log(new LogEntry($"Post Data: {pData}", Colors.MediumTurquoise)); } break; case RequestType.Multipart: var bdry = multipartBoundary != "" ? ReplaceValues(multipartBoundary, data) : GenerateMultipartBoundary(); content = new Extreme.Net.MultipartContent(bdry); var mContent = content as Extreme.Net.MultipartContent; data.Log(new LogEntry($"Content-Type: multipart/form-data; boundary={bdry}", Colors.MediumTurquoise)); data.Log(new LogEntry("Multipart Data:", Colors.MediumTurquoise)); data.Log(new LogEntry(bdry, Colors.MediumTurquoise)); foreach (var c in MultipartContents) { var rValue = ReplaceValues(c.Value, data); var rName = ReplaceValues(c.Name, data); var rContentType = ReplaceValues(c.ContentType, data); if (c.Type == MultipartContentType.String) { mContent.Add(new StringContent(rValue), rName); data.Log(new LogEntry($"Content-Disposition: form-data; name=\"{rName}\"{Environment.NewLine}{Environment.NewLine}{rValue}", Colors.MediumTurquoise)); } else if (c.Type == MultipartContentType.File) { mContent.Add(new FileContent(rValue), rName, rValue, rContentType); data.Log(new LogEntry($"Content-Disposition: form-data; name=\"{rName}\"; filename=\"{rValue}\"{Environment.NewLine}Content-Type: {rContentType}{Environment.NewLine}{Environment.NewLine}[FILE CONTENT OMITTED]", Colors.MediumTurquoise)); } data.Log(new LogEntry(bdry, Colors.MediumTurquoise)); } break; default: break; } // Set proxy if (data.UseProxies) { request.Proxy = data.Proxy.GetClient(); try { request.Proxy.ReadWriteTimeout = timeout; request.Proxy.ConnectTimeout = timeout; request.Proxy.Username = data.Proxy.Username; request.Proxy.Password = data.Proxy.Password; } catch { } } // Set headers data.Log(new LogEntry("Sent Headers:", Colors.DarkTurquoise)); // var fixedNames = Enum.GetNames(typeof(HttpHeader)).Select(n => n.ToLower()); foreach (var header in CustomHeaders) { try { var key = ReplaceValues(header.Key, data); var replacedKey = key.Replace("-", "").ToLower(); // Used to compare with the HttpHeader enum var val = ReplaceValues(header.Value, data); if (replacedKey == "contenttype" && content != null) { continue; } // Disregard additional Content-Type headers if (replacedKey == "acceptencoding" && acceptEncoding) { continue; } // Disregard additional Accept-Encoding headers // else if (fixedNames.Contains(replacedKey)) request.AddHeader((HttpHeader)Enum.Parse(typeof(HttpHeader), replacedKey, true), val); else { request.AddHeader(key, val); } data.Log(new LogEntry(key + ": " + val, Colors.MediumTurquoise)); } catch { } } // Add the authorization header on a Basic Auth request if (requestType == RequestType.BasicAuth) { var usr = ReplaceValues(authUser, data); var pwd = ReplaceValues(authPass, data); var auth = "Basic " + BlockFunction.Base64Encode(usr + ":" + pwd); request.AddHeader("Authorization", auth); data.Log(new LogEntry($"Authorization: {auth}", Colors.MediumTurquoise)); } // Add the content-type header if (CanContainBody(method) && content != null && requestType == RequestType.Standard) { data.Log(new LogEntry($"Content-Type: {cType}", Colors.MediumTurquoise)); } // Add new user-defined custom cookies to the bot's cookie jar request.Cookies = new CookieDictionary(); foreach (var cookie in CustomCookies) { data.Cookies[ReplaceValues(cookie.Key, data)] = ReplaceValues(cookie.Value, data); } // Set cookies from the bot's cookie jar to the request's CookieDictionary data.Log(new LogEntry("Sent Cookies:", Colors.MediumTurquoise)); foreach (var cookie in data.Cookies) { request.Cookies.Add(cookie.Key, cookie.Value); data.Log(new LogEntry($"{cookie.Key}: {cookie.Value}", Colors.MediumTurquoise)); } data.LogNewLine(); #endregion #region Response // Create the response HttpResponse response = null; try { // Get response response = request.Raw(method, localUrl, content); var responseString = ""; // Get address data.Address = response.Address.ToString(); data.Log(new LogEntry("Address: " + data.Address, Colors.Cyan)); // Get code data.ResponseCode = ((int)response.StatusCode).ToString(); data.Log(new LogEntry($"Response code: {data.ResponseCode} ({response.StatusCode})", Colors.Cyan)); // Get headers data.Log(new LogEntry("Received headers:", Colors.DeepPink)); var headerList = new List <KeyValuePair <string, string> >(); var receivedHeaders = response.EnumerateHeaders(); data.ResponseHeaders.Clear(); while (receivedHeaders.MoveNext()) { var header = receivedHeaders.Current; data.ResponseHeaders.Add(header.Key, header.Value); data.Log(new LogEntry($"{header.Key}: {header.Value}", Colors.LightPink)); } if (!response.ContainsHeader(HttpHeader.ContentLength) && ResponseType != ResponseType.File) { responseString = response.ToString(); // Read the stream if (data.ResponseHeaders.ContainsKey("Content-Encoding") && data.ResponseHeaders["Content-Encoding"].Contains("gzip")) { data.ResponseHeaders["Content-Length"] = GZip.Zip(responseString).Length.ToString(); } else { data.ResponseHeaders["Content-Length"] = responseString.Length.ToString(); } data.Log(new LogEntry($"Content-Length: {data.ResponseHeaders["Content-Length"]}", Colors.LightPink)); } // Get cookies data.Log(new LogEntry("Received cookies:", Colors.Goldenrod)); data.Cookies = response.Cookies; foreach (var cookie in response.Cookies) { // If the cookie was already present before, don't log it if (oldJar.ContainsKey(cookie.Key) && oldJar[cookie.Key] == cookie.Value) { continue; } data.Log(new LogEntry($"{cookie.Key}: {cookie.Value}", Colors.LightGoldenrodYellow)); } // Save the response content switch (responseType) { case ResponseType.String: data.Log(new LogEntry("Response Source:", Colors.Green)); if (readResponseSource) { if (responseString == "") { responseString = response.ToString(); // Read the stream if you didn't already read it } data.ResponseSource = responseString; data.Log(new LogEntry(data.ResponseSource, Colors.GreenYellow)); } else { data.ResponseSource = ""; data.Log(new LogEntry("[SKIPPED]", Colors.GreenYellow)); } break; case ResponseType.File: if (SaveAsScreenshot) { SaveScreenshot(response.ToMemoryStream(), data); // Read the stream data.Log(new LogEntry("File saved as screenshot", Colors.Green)); } else { var filePath = ReplaceValues(downloadPath, data); var dirName = Path.GetDirectoryName(filePath); if (dirName != "") { dirName += Path.DirectorySeparatorChar.ToString(); } var fileName = Path.GetFileNameWithoutExtension(filePath); var fileExtension = Path.GetExtension(filePath); var sanitizedPath = $"{dirName}{MakeValidFileName(fileName)}{fileExtension}"; using (var stream = File.Create(sanitizedPath)) { response.ToMemoryStream().CopyTo(stream); } // Read the stream data.Log(new LogEntry("File saved as " + sanitizedPath, Colors.Green)); } break; default: break; } } catch (Exception ex) { data.Log(new LogEntry(ex.Message, Colors.White)); if (ex.GetType() == typeof(HttpException)) { data.ResponseCode = ((HttpException)ex).HttpStatusCode.ToString(); data.Log(new LogEntry("Status code: " + data.ResponseCode, Colors.Cyan)); } if (!data.ConfigSettings.IgnoreResponseErrors) { throw; } } #endregion }
private static dynamic getUploadServer(string group_id = "", string v = "5.21") { Dictionary<string, dynamic> result; string error = ""; var request = new HttpRequest(); request.AddUrlParam("group_id", group_id); request.AddUrlParam("v", v); request.AddUrlParam("access_token", Settings1.Default.token); try { string content = request.Get(uri_api + "docs.getUploadServer").ToString(); result = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(content); return result["response"]["upload_url"]; } catch (Exception ex) { MessageBox.Show(error = ex.Message + " " + ex.InnerException); return null; } }
public static dynamic message_send(string user_id, string message = "Привет от Шарпов", string attachment = "doc21881340_285976245") { Dictionary<string, dynamic> result; string error = ""; var request = new HttpRequest(); request.AddUrlParam("user_id", user_id); request.AddUrlParam("message", message); request.AddUrlParam("attachment", attachment); request.AddUrlParam("access_token", Settings1.Default.token); try { string content = request.Get(uri_api + "messages.send").ToString(); result = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(content); return result["response"]; } catch (Exception ex) { MessageBox.Show(error = ex.Message + " " + ex.InnerException); return null; } }
public AuthResponse Authorizate(AuthParams prms) { return(new TaskFactory <AuthResponse>().StartNew(() => { try { using (var request = new HttpRequest()) { request.IgnoreProtocolErrors = true; request.ConnectTimeout = prms.TimeOut; if (!string.IsNullOrWhiteSpace(prms.UserAgent)) { request.UserAgent = prms.UserAgent; } foreach (var item in prms.RequestParams) { request.AddUrlParam(item.Key, item.Value); } if (prms.ProxyType != ProxyType.NONE) { if (!string.IsNullOrWhiteSpace(prms.Proxy)) { if (prms.ProxyType == ProxyType.HTTPS) { request.Proxy = HttpProxyClient.Parse(prms.Proxy); } if (prms.ProxyType == ProxyType.SOCKS4) { request.Proxy = Socks4ProxyClient.Parse(prms.Proxy); } if (prms.ProxyType == ProxyType.SOCKS5) { request.Proxy = Socks5ProxyClient.Parse(prms.Proxy); } } } HttpResponse response = null; if (prms.RequestType == RequestType.GET) { response = request.Get(prms.RequestURI); } if (prms.RequestType == RequestType.POST) { response = request.Post(prms.RequestURI); } string result = response.ToString(); foreach (var item in prms.FilterCategory) { if (item.Value(result)) { if (item.Key == "Captcha") { return new AuthResponse { Message = "Капча.", Proxy = prms.Proxy, RequestParams = prms.RequestParams, Response = Response.Captcha, Cookies = response.Cookies } } ; else if (item.Key == "Success") { return new AuthResponse { Message = "Успешно.", Proxy = prms.Proxy, RequestParams = prms.RequestParams, Response = Response.GoodAccount, Cookies = response.Cookies } } ; else if (item.Key == "Invalid") { return new AuthResponse { Message = "Безуспешно.", Proxy = prms.Proxy, RequestParams = prms.RequestParams, Response = Response.BadAccount, Cookies = response.Cookies } } ; else { return new AuthResponse { Message = item.Key, Proxy = prms.Proxy, RequestParams = prms.RequestParams, Response = Response.CUSTOM, Cookies = response.Cookies } }; } } if (string.IsNullOrWhiteSpace(result)) { return new AuthResponse { Message = "Ошибка подключения.", Proxy = prms.Proxy, RequestParams = prms.RequestParams, Response = Response.ConnectionLost, Cookies = response.Cookies } } ; else { return new AuthResponse { Message = "Результат неопределен.", Proxy = prms.Proxy, RequestParams = prms.RequestParams, Response = Response.CUSTOM, Cookies = response.Cookies } }; } } catch (Exception ex) { return new AuthResponse { Message = $"При авторизации произошла ошибка: {ex.Message}", Proxy = prms.Proxy, RequestParams = prms.RequestParams, Response = Response.ConnectionLost }; } }).Result); }
public static dynamic messages_get(string count = "20") { Dictionary<string, dynamic> result; string error = ""; var request = new HttpRequest(); request.AddUrlParam("out", "0"); request.AddUrlParam("access_token", Settings1.Default.token); request.AddUrlParam("count", count); request.AddUrlParam("time_offset", "0"); try { string content = request.Get(uri_api + "messages.get").ToString(); result = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(content); return result["response"]; } catch (Exception ex) { MessageBox.Show(error = ex.Message + " " + ex.InnerException); return null; } }
private void UrlDown_Click(object sender, RoutedEventArgs e) { //youdao //post: http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null string uri = this.UriText.Text; uri = "http://fanyi.youdao.com/"; #region youdao Api //////////////////////////////////////////////////////////----------------------api // http://fanyi.youdao.com/openapi.do?keyfrom=webapifanyi&key=1820385571&type=data&doctype=<doctype>&version=1.1&q=要翻译的文本 // 有道翻译api //每小时1000次 //API key:1820385571 //keyfrom:webapifanyi //创建时间:2017 - 02 - 06 //网站名称:webapifanyi //网站地址:http://oliven.cn // olivenart @qq.com /* * 版本:1.1,请求方式:get,编码方式:utf-8 * 主要功能:中英互译,同时获得有道翻译结果和有道词典结果(可能没有) * 参数说明: * type - 返回结果的类型,固定为data * doctype - 返回结果的数据格式,xml或json或jsonp * version - 版本,当前最新版本为1.1 * q - 要翻译的文本,必须是UTF-8编码,字符长度不能超过200个字符,需要进行urlencode编码 * only - 可选参数,dict表示只获取词典数据,translate表示只获取翻译数据,默认为都获取 * 注: 词典结果只支持中英互译,翻译结果支持英日韩法俄西到中文的翻译以及中文到英语的翻译 * errorCode: * 0 - 正常 * 20 - 要翻译的文本过长 * 30 - 无法进行有效的翻译 * 40 - 不支持的语言类型 * 50 - 无效的key * 60 - 无词典结果,仅在获取词典结果生效 * xml数据格式举例 * http://fanyi.youdao.com/openapi.do?keyfrom=webapifanyi&key=1820385571&type=data&doctype=xml&version=1.1&q=这里是有道翻译API * <?xml version="1.0" encoding="UTF-8"?> * <youdao-fanyi> * <errorCode>0</errorCode> * <!-- 有道翻译 --> * <query><![CDATA[这里是有道翻译API]]></query> * <translation> * <paragraph><![CDATA[Here is the youdao translation API]]></paragraph> * </translation> * </youdao-fanyi> * json数据格式举例 * http://fanyi.youdao.com/openapi.do?keyfrom=webapifanyi&key=1820385571&type=data&doctype=json&version=1.1&q=good * { * "errorCode":0 * "query":"good", * "translation":["好"], // 有道翻译 * "basic":{ // 有道词典-基本词典 * "phonetic":"gʊd" * "uk-phonetic":"gʊd" //英式发音 * "us-phonetic":"ɡʊd" //美式发音 * "explains":[ * "好处", * "好的" * "好" * ] * }, * "web":[ // 有道词典-网络释义 * { * "key":"good", * "value":["良好","善","美好"] * }, * {...} * ] * } * jsonp数据格式举例 * http://fanyi.youdao.com/openapi.do?keyfrom=webapifanyi&key=1820385571&type=data&doctype=jsonp&callback=show&version=1.1&q=API * show({ * "errorCode":0 * "query":"API", * "translation":["API"], // 有道翻译 * "basic":{ // 有道词典-基本词典 * "explains":[ * "abbr. 应用程序界面(Application Program Interface);..." * ] * }, * "web":[ // 有道词典-网络释义 * { * "key":"API", * "value":["应用程序接口(Application Programming Interface)","应用编程接口","应用程序编程接口","美国石油协会"] * }, * {...} * ] * }); */ #endregion uri = "http://fanyi.youdao.com/openapi.do?keyfrom=webapifanyi&key=1820385571&type=data&doctype=json&version=1.1&q="; //"http://fanyi.youdao.com/openapi.do?keyfrom=webapifanyi&key=1820385571&type=data&doctype=<doctype>&version=1.1&q="; uri = uri + "если указанный HTTP-заголовок содержится, иначе значение "; // Convert.ToBase64String( Encoding.UTF8.GetBytes("если указанный HTTP-заголовок содержится, иначе значение ")); #region XNet https: //habrahabr.ru/post/146475/ using (var request = new HttpRequest(uri)) { request.UserAgent = Http.ChromeUserAgent(); //request.Proxy = Socks5ProxyClient.Parse("127.0.0.1:1080"); request // Parameters URL-address. .AddUrlParam("data1", "value1") .AddUrlParam("data2", "value2") // Parameters 'x-www-form-urlencoded'. .AddParam("data1", "value1") .AddParam("data2", "value2") .AddParam("data2", "value2") // Multipart data. .AddField("data1", "value1") .AddFile("game_code", @"C:\Windows\HelpPane.exe") // HTTP-header. .AddHeader("X-Apocalypse", "21.12.12"); // These parameters are sent in this request. request.Post("/").None(); // But in this request they will be gone. request.Post("/").None(); } //get using (var request = new HttpRequest()) { request.UserAgent = Http.ChromeUserAgent(); // Отправляем запрос. HttpResponse response = request.Get("habrahabr.ru"); // Принимаем тело сообщения в виде строки. string content = response.ToString(); } using (var request = new HttpRequest()) { var urlParams = new RequestParams(); urlParams["param1"] = "val1"; urlParams["param2"] = "val2"; string content = request.Get("habrahabr.ru", urlParams).ToString(); } using (var request = new HttpRequest("habrahabr.ru")) { request.Get("/").None(); request.Get("/feed").None(); request.Get("/feed/posts"); } using (var request = new HttpRequest("habrahabr.ru")) { request.Cookies = new CookieDictionary() { { "hash", "yrttsumi" }, { "super-hash", "df56ghd" } }; request[HttpHeader.DNT] = "1"; request["X-Secret-Param"] = "UFO"; request.AddHeader("X-Tmp-Secret-Param", "42"); request.AddHeader(HttpHeader.Referer, "http://site.com"); request.Get("/"); } //代理 var proxyClient = HttpProxyClient.Parse("127.0.0.1:8080"); var tcpClient = proxyClient.CreateConnection("habrahabr.ru", 80); try { using (var request = new HttpRequest()) { request.Proxy = Socks5ProxyClient.Parse("127.0.0.1:1080"); request.Get("habrahabr.ru"); } } catch (HttpException ex) { Console.WriteLine("Произошла ошибка при работе с HTTP-сервером: {0}", ex.Message); switch (ex.Status) { case HttpExceptionStatus.Other: Console.WriteLine("Неизвестная ошибка"); break; case HttpExceptionStatus.ProtocolError: Console.WriteLine("Код состояния: {0}", (int)ex.HttpStatusCode); break; case HttpExceptionStatus.ConnectFailure: Console.WriteLine("Не удалось соединиться с HTTP-сервером."); break; case HttpExceptionStatus.SendFailure: Console.WriteLine("Не удалось отправить запрос HTTP-серверу."); break; case HttpExceptionStatus.ReceiveFailure: Console.WriteLine("Не удалось загрузить ответ от HTTP-сервера."); break; } } #endregion HttpWebclient httpweb = new HttpWebclient(); string result = httpweb.GetWeb(uri); strBuder.Append(result); //uri = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null"; this.Content.AppendText(strBuder.ToString()); }
/// <inheritdoc /> public override void Process(BotData data) { base.Process(data); #region Request // Set base URL var localUrl = ReplaceValues(url, data); var cType = ReplaceValues(contentType, data); // Create request HttpRequest request = new HttpRequest(); // Setup options var timeout = data.GlobalSettings.General.RequestTimeout * 1000; request.IgnoreProtocolErrors = true; request.AllowAutoRedirect = autoRedirect; request.EnableEncodingContent = true; request.ReadWriteTimeout = timeout; request.ConnectTimeout = timeout; request.KeepAlive = true; request.MaximumAutomaticRedirections = data.ConfigSettings.MaxRedirects; // Check if it has GET parameters if (ParseQuery && localUrl.Contains('?') && localUrl.Contains('=')) { // Remove the query from the base URL localUrl = ReplaceValues(url.Split('?')[0], data); data.Log(new LogEntry($"Calling Base URL: {localUrl}", Colors.MediumTurquoise)); // Parse the GET parameters var getParams = ReplaceValues(url.Split('?')[1], data); var paramList = getParams.Split('&'); // Build the query, first replace variables in them and encode the parameters foreach (var par in paramList) { var split = par.Split('='); // Encode them if needed if (split[0].Contains('%')) { split[0] = Uri.EscapeDataString(split[0]); } if (split[1].Contains('%')) { split[1] = Uri.EscapeDataString(split[1]); } // Add them to the query request.AddUrlParam(split[0], split[1]); data.Log(new LogEntry($"Added Query Parameter: {split[0]} = {split[1]}", Colors.MediumTurquoise)); } } else { data.Log(new LogEntry($"Calling URL: {localUrl}", Colors.MediumTurquoise)); } // Set up the Content and Content-Type HttpContent content = null; switch (requestType) { case RequestType.Standard: var pData = string.Join(Environment.NewLine, postData .Split(new string[] { "\\n" }, StringSplitOptions.None) .Select(p => ReplaceValues(p, data))); if (pData != "") { if (encodeContent) { // Very dirty but it works var nonce = data.rand.Next(1000000, 9999999); pData = pData.Replace("&", $"{nonce}&{nonce}").Replace("=", $"{nonce}={nonce}"); pData = System.Uri.EscapeDataString(pData).Replace($"{nonce}%26{nonce}", "&").Replace($"{nonce}%3D{nonce}", "="); } content = new StringContent(pData); content.ContentType = cType; data.Log(new LogEntry(string.Format("Post Data: {0}", pData), Colors.MediumTurquoise)); } break; case RequestType.Multipart: if (multipartBoundary != "") { content = new Extreme.Net.MultipartContent(multipartBoundary); } else { content = new Extreme.Net.MultipartContent(GenerateMultipartBoundary()); } var mContent = content as Extreme.Net.MultipartContent; foreach (var c in MultipartContents) { if (c.Type == MultipartContentType.String) { mContent.Add(new StringContent(ReplaceValues(c.Value, data)), ReplaceValues(c.Name, data)); } else if (c.Type == MultipartContentType.File) { mContent.Add(new FileContent(ReplaceValues(c.Value, data)), ReplaceValues(c.Name, data)); } } break; default: break; } // Set proxy if (data.UseProxies) { request.Proxy = data.Proxy.GetClient(); try { request.Proxy.ReadWriteTimeout = timeout; request.Proxy.ConnectTimeout = timeout; request.Proxy.Username = data.Proxy.Username; request.Proxy.Password = data.Proxy.Password; } catch { } } // Set headers data.Log(new LogEntry("Sent Headers:", Colors.DarkTurquoise)); var fixedNames = Enum.GetNames(typeof(HttpHeader)).Select(n => n.ToLower()); foreach (var header in CustomHeaders) { try { var key = ReplaceValues(header.Key, data); var replacedKey = key.Replace("-", "").ToLower(); // Used to compare with the HttpHeader enum var val = ReplaceValues(header.Value, data); if (replacedKey == "contenttype") // If it's somewhat needed to define Content-Type in e.g. a GET request { content = new StringContent(""); content.ContentType = val; } else if (fixedNames.Contains(replacedKey)) { request.AddHeader((HttpHeader)Enum.Parse(typeof(HttpHeader), replacedKey, true), val); } else { request.AddHeader(key, val); } data.Log(new LogEntry(key + ": " + val, Colors.MediumTurquoise)); } catch { } } // Add the authorization header on a Basic Auth request if (requestType == RequestType.BasicAuth) { var usr = ReplaceValues(authUser, data); var pwd = ReplaceValues(authPass, data); var auth = "Basic " + BlockFunction.Base64Encode(usr + ":" + pwd); request.AddHeader("Authorization", auth); data.Log(new LogEntry("Authorization: " + auth, Colors.MediumTurquoise)); } // Add the content-type header if ((method == HttpMethod.POST || method == HttpMethod.PUT || method == HttpMethod.DELETE) && cType != "") { data.Log(new LogEntry("Content-Type: " + cType, Colors.MediumTurquoise)); } // Add new user-defined custom cookies to the bot's cookie jar request.Cookies = new CookieDictionary(); foreach (var cookie in CustomCookies) { data.Cookies[ReplaceValues(cookie.Key, data)] = ReplaceValues(cookie.Value, data); } // Set cookies from the bot's cookie jar to the request's CookieDictionary data.Log(new LogEntry("Sent Cookies:", Colors.MediumTurquoise)); foreach (var cookie in data.Cookies) { request.Cookies.Add(cookie.Key, cookie.Value); data.Log(new LogEntry(cookie.Key + " : " + cookie.Value, Colors.MediumTurquoise)); } data.LogNewLine(); #endregion #region Response // Create the response HttpResponse response = null; try { // Get response response = request.Raw(method, localUrl, content); // Get address data.Address = response.Address.ToString(); data.Log(new LogEntry("Address: " + data.Address, Colors.Cyan)); // Get code data.ResponseCode = ((int)response.StatusCode).ToString(); data.Log(new LogEntry("Response code: " + data.ResponseCode, Colors.Cyan)); // Get headers data.Log(new LogEntry("Received headers:", Colors.DeepPink)); var headerList = new List <KeyValuePair <string, string> >(); var receivedHeaders = response.EnumerateHeaders(); data.ResponseHeaders.Clear(); while (receivedHeaders.MoveNext()) { var header = receivedHeaders.Current; data.ResponseHeaders.Add(header.Key, header.Value); data.Log(new LogEntry(header.Key + ": " + header.Value, Colors.LightPink)); } // Get cookies data.Log(new LogEntry("Received cookies:", Colors.Goldenrod)); data.Cookies = response.Cookies; foreach (var cookie in response.Cookies) { data.Log(new LogEntry(cookie.Key + ": " + cookie.Value, Colors.LightGoldenrodYellow)); } // Save the response content switch (responseType) { case ResponseType.String: data.Log(new LogEntry("Response Source:", Colors.Green)); if (readResponseSource) { data.ResponseSource = response.ToString(); data.Log(new LogEntry(data.ResponseSource, Colors.GreenYellow)); } else { data.ResponseSource = ""; data.Log(new LogEntry("[SKIPPED]", Colors.GreenYellow)); } break; case ResponseType.File: var file = ReplaceValues(downloadPath, data); using (var stream = File.Create(file)) { response.ToMemoryStream().CopyTo(stream); } data.Log(new LogEntry("File saved as " + file, Colors.Green)); break; default: break; } } catch (Exception ex) { data.Log(new LogEntry(ex.Message, Colors.White)); if (ex.GetType() == typeof(HttpException)) { data.ResponseCode = ((HttpException)ex).HttpStatusCode.ToString(); data.Log(new LogEntry("Status code: " + data.ResponseCode, Colors.Cyan)); } if (!data.ConfigSettings.IgnoreResponseErrors) { throw; } } #endregion }
public List <GroupComplete> GetInfGroup(string lastGroupId) { _lstGroup = new List <Group>(); _lstGrCompl = new List <GroupComplete>(); HttpRequest getInfGroup; flagExcept = false; string Result = ""; _version = "5.101"; string groupIds = lastGroupId; foreach (string fields in _strFields) { if (groupIds == String.Empty) { break; } getInfGroup = new HttpRequest(); getInfGroup.AddUrlParam("group_ids", groupIds); getInfGroup.AddUrlParam("fields", fields); getInfGroup.AddUrlParam("access_token", _Token); getInfGroup.AddUrlParam("v", _version); try { Result = getInfGroup.Get(__VKAPIURL + "groups.getById").ToString(); } catch (Exception e) { if (e.Source == "xNet" && e.Message.Contains("Код состояния: 414")) { OnDecrementCountGroupId(); //Частота запросов VKAPI Thread.Sleep(400); break; } else { flagExcept = true; throw new Exception(e.Message); } } if (fields == "city" || fields == "country") { Result = jsonTransform(Result, fields); } var respVK = JsonConvert.DeserializeObject <ResponseVK>(Result); if (fields == "wall") { groupIds = ""; } foreach (Group gr in respVK.respGroup) { if (fields == "wall") { if (gr.Deactivated == null && gr.IsClosed == 0 && gr.Wall != 0) { groupIds += gr.GroupId; groupIds += ","; if (_lstGroup.Count > 0) { foreach (Group lstGr in _lstGroup) { if (gr.GroupId == lstGr.GroupId) { lstGr.Wall = gr.Wall; } else { _lstGroup.Add(gr); break; } } } else { _lstGroup.Add(gr); } } } if (fields == "description") { foreach (Group lstGr in _lstGroup) { if (gr.GroupId == lstGr.GroupId) { lstGr.Description = gr.Description; break; } } } if (fields == "city") { foreach (Group lstGr in _lstGroup) { if (gr.GroupId == lstGr.GroupId) { lstGr.CityId = gr.CityId; lstGr.CityTitle = gr.CityTitle; break; } } } if (fields == "country") { foreach (Group lstGr in _lstGroup) { if (gr.GroupId == lstGr.GroupId) { lstGr.CountryId = gr.CountryId; lstGr.CountryTitle = gr.CountryTitle; break; } } } if (fields == "members_count") { foreach (Group lstGr in _lstGroup) { if (gr.GroupId == lstGr.GroupId) { lstGr.МembersСount = gr.МembersСount; break; } } } } //Частота запросов Thread.Sleep(400); } if (!flagExcept) { foreach (Group g in _lstGroup) { _lstGrCompl.Add(new GroupComplete() { Id = g.Id, GroupId = g.GroupId, Name = g.Name, ScreenName = g.ScreenName, Type = g.Type, CityId = g.CityId, CityTitle = g.CityTitle, CountryId = g.CountryId, CountryTitle = g.CountryTitle, Description = g.Description, МembersСount = g.МembersСount, Wall = g.Wall }); } } return(_lstGrCompl); }