public HttpResponse Post(HttpRequest request, string uploadUrl, string path) { request.AddFile("photo", path); var response = request.Post(uploadUrl); return(response); }
public static string uploadPhoto(string PathPhoto, string upload_url) { HttpRequest request = new HttpRequest(); request.AddFile("photo", PathPhoto, PathPhoto); string response = request.Post(upload_url).ToString(); return(response); }
/// <summary> /// Оправляет multipart/form-data на заданный url /// <PARAM name="url">Адрес url</PARAM> /// <PARAM name="pData">PostData</PARAM> /// </summary> private void SendMultipartFormdata(string url, PostData pData) { Logger.Debug(tmSettings, "smfd mt wait", false, mutLogger); mutAPI.WaitOne(); Logger.Debug(tmSettings, "smfd mt success", false, mutLogger); HttpRequest request = CreateRequest(); request.KeepAlive = true; foreach (PostDataParam param in pData.Params) { if (param.Type == PostDataParamType.Field) { request.AddField(param.Name, param.Value); } else { request.AddFile(param.Name, param.Value); } } Logger.Debug(tmSettings, "smfd post request", false, mutLogger); //HttpResponse response = request.Send(HttpMethod.POST, new Uri(String.Format(url, botToken))); HttpResponse response = request.Post(String.Format(url, botToken)); string jsonText = response.ToString(); response.None(); response = null; Logger.Debug(tmSettings, "smfd answer to response: " + jsonText, false, mutLogger); TelegramAnswerMessage answer = JsonConvert.DeserializeObject <TelegramAnswerMessage>(jsonText); Logger.Debug(tmSettings, "smfd " + answer.ok.ToString(), false, mutLogger); if (!answer.ok) { Logger.Write(answer.description, true, mutLogger); } else { SaveMessageToDB(answer.message, "out"); } request.Close(); request = null; mutAPI.ReleaseMutex(); Logger.Debug(tmSettings, "smfd mt release", false, mutLogger); GC.WaitForPendingFinalizers(); GC.Collect(); }
static void Main() { var url = "http://*****:*****@"D:\11111.docx"; using (var request = new HttpRequest()) { request.AddFile("data", filePath); try { var response = request.Post(url); Console.WriteLine(response.ToString()); } catch (Exception exception) { Console.WriteLine(exception.Message); } } }
public static UploadPhoto GetUploadPhoto(string pathPhoto, string upload_url) { request.AddFile("photo", pathPhoto, pathPhoto); HttpResponse response = request.Post(upload_url); string content = response.ToString(); #region Проверяем не вернулся ли другой JSON (ошибка) JObject o = JObject.Parse(content); if (o.ContainsKey("error")) { string error = o.ContainsKey("error").ToString(); switch (error) { case "":; break; //TODO: Узнать модель ошибки //throw new Exception(error); default: throw new Exception($"Непредвиденная ошибка {error} \n {response.Address.ToString()}"); } } #endregion return(JsonConvert.DeserializeObject <UploadPhoto>(content)); }
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; } }
private void button1_send_Click_1(object sender, EventArgs e) { string groupId = af.GetGroupId; string message = richTextBox1.Text; string userToken = af.GetUserToken; string userId = af.GetUserId; string postPhotoUrl = "https://api.vk.com/method/photos.getWallUploadServer?group_id=" + groupId + "&access_token=" + userToken + "&v=5.103"; string postPhotoRespond = SendRequest(postPhotoUrl); string uriSend = postPhotoRespond.Substring(postPhotoRespond.IndexOf("http")); uriSend = uriSend.Substring(0, uriSend.IndexOf("user_id") - 3); while (uriSend.IndexOf("\\/") != -1) { uriSend = uriSend.Remove(uriSend.IndexOf("\\/"), 1); } HttpRequest req = new HttpRequest(); req.AddFile("photo", @pictureBox1.ImageLocation); HttpResponse response = req.Post(uriSend); richTextBox2_debug.Text = Convert.ToString(response); string s = richTextBox2_debug.Text; while (s.IndexOf("\\\"") != -1) { s = s.Remove(s.IndexOf("\\\""), 1); } string server = s.Substring(s.IndexOf("server") + 8); server = server.Remove(server.IndexOf(",\"photo\":\"")); string photo = s.Substring(s.IndexOf(",\"photo\":\"") + 10); photo = photo.Remove(photo.IndexOf("\",\"hash")); string hash = s.Substring(s.IndexOf("\",\"hash\":\"") + 10); hash = hash.Remove(hash.IndexOf("\"}")); string reqUrl = "https://api.vk.com/method/photos.saveWallPhoto?group_id=" + groupId + "&user_id" + userId + "&photo=" + photo + "&server=" + server + "&hash=" + hash + "&access_token=" + userToken + "&v=5.103"; string saveResp = SendRequest(reqUrl); string photoId = saveResp.Substring(saveResp.IndexOf(":[{\"id\":") + 8); photoId = photoId.Remove(photoId.IndexOf(",\"album_id")); string ownerId = saveResp.Substring(saveResp.IndexOf("owner_id") + 10); ownerId = ownerId.Remove(ownerId.IndexOf(",\"sizes\":[{")); string urlWallpost = "https://api.vk.com/method/wall.post?owner_id=-" + groupId + "&message=" + message + "&attachments=photo" + ownerId + "_" + photoId + "&access_token=" + userToken + "&v=5.103"; string warrPostResp = SendRequest(urlWallpost); if (warrPostResp.IndexOf("post_id") != -1) { MessageBox.Show("Posted"); } else { MessageBox.Show("Error"); } }
/// <summary> /// Отправляет на антигейт массив данных изображения в формате PNG. /// /// </summary> /// <param name="ImageData">Массив данных изображения (PNG)</param> /// <param name="ct">CancellationToken</param> /// <returns> /// Разгаданный текст капчи или [null] в случае отсутствия свободных слотов или превышения времени ожидания /// </returns> public async Task <string> GetAnswer(byte[] ImageData, CancellationToken ct) { if (ImageData == null || ImageData.Length == 0) { throw new ArgumentException("Image data array is empty"); } var num = SlotRetry; CaptchaId = null; string str; var req = new HttpRequest(); while (true) { if (ct.IsCancellationRequested) { ct.ThrowIfCancellationRequested(); } req.AddField("method", "post"); req.AddField("key", Key); req.AddField("soft_id", "1151"); req.AddFile("file", "image.jpg", "image/jpeg", ImageData); if (Parameters.Count > 0) { foreach (Param obj in Parameters.GetParams()) { req.AddField(obj.Key, obj.Value, Encoding.UTF8); } } try { str = req.Post($"http://{ServiceProvider}/in.php").ToString(); } catch { throw new WebException("Antigate server did not respond"); } if (str.Equals("ERROR_NO_SLOT_AVAILABLE", StringComparison.InvariantCultureIgnoreCase)) { if (num - 1 > 0) { --num; Thread.Sleep(SlotRetryDelay); } else { break; } } else { goto label_22; } } throw new WebException(str); label_22: if (str.StartsWith("ERROR_", StringComparison.InvariantCultureIgnoreCase)) { throw new AntigateErrorException( (AntigateError)Enum.Parse(typeof(AntigateError), str.Substring(6))); } try { CaptchaId = str.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)[1]; } catch { throw new WebException("Antigate answer is in unknown format or malformed"); } for (var index = 0; index < CheckRetryCount; ++index) { await Task.Delay(CheckDelay, ct); str = req.Get($"http://{ServiceProvider}/res.php?key={Key}&action=get&id={CaptchaId}").ToString(); if (str.Equals("CAPCHA_NOT_READY", StringComparison.InvariantCultureIgnoreCase)) { continue; } if (str.StartsWith("ERROR_", StringComparison.InvariantCultureIgnoreCase)) { throw new AntigateErrorException( (AntigateError)Enum.Parse(typeof(AntigateError), str.Substring(6))); } var strArray = str.Split('|'); if (strArray[0].Equals("OK", StringComparison.InvariantCultureIgnoreCase)) { return(strArray[1]); } } return(null); }