POST загрузка изображения на сервер VK - C#
Формулировка задачи:
Не получается передать изображение на сервер VK (Windows 8). В ответ от сервера я получаю пустую строку photo_list[]. Проблема в загрузке изображения, но какая именно не знаю. Код:
private async void Button_Click(object sender, RoutedEventArgs e) { string oauthUrl = "http://cs319216.vk.com/upload.php?act=do_add&mid=2314852&aid=169819278&gid=37273781&hash=82c465709a9b754e44ba2b4a4c27426a&rhash=235249149115419e40ada041ab7e2037&swfupload=1&api=1&save_big=1"; HttpClient theAuthClient = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, oauthUrl); StorageFolder storageFolder = KnownFolders.PicturesLibrary; StorageFile sf = await storageFolder.GetFileAsync("ss.png"); IBuffer buffer = await FileIO.ReadBufferAsync(sf); byte[] fileData = buffer.ToArray(); Encoding encoding = Encoding.GetEncoding("Windows-1252"); string text = encoding.GetString(fileData, 0, fileData.Length); string content = "file1=" + text + ""; txt.Text = content; request.Method = HttpMethod.Post; request.Content = new StreamContent(new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(content))); request.Content.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); try { HttpResponseMessage response = await theAuthClient.SendAsync(request); handleResponse(response); } catch (HttpRequestException hre) { } } public async void handleResponse(HttpResponseMessage response) { string content = await response.Content.ReadAsStringAsync(); Account account = JsonConvert.DeserializeObject<Account>(content); if (content != null) { } }
Решение задачи: «POST загрузка изображения на сервер VK»
textual
Листинг программы
Код загрузки фотографии на сервер: //ЗАГРУЗКА ФОТОГРАФИИ //получение адреса сервера для загрузки фотографии System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; System.Net.WebRequest post_request2 = System.Net.WebRequest.Create("https://api.vkontakte.ru/method/photos.getWallUploadServer?gid=100669061&access_token=" + textBox3.Text.Trim()); System.Net.WebResponse post_request_response2 = post_request2.GetResponse(); System.IO.Stream post_request_stream2 = post_request_response2.GetResponseStream(); System.IO.StreamReader post_request_stream_reader2 = new System.IO.StreamReader(post_request_stream2); string post_request_answer2 = post_request_stream_reader2.ReadToEnd(); string[] words_empty = post_request_answer2.Split('"'); string s = words_empty[5]; s = s.Replace("\\/","/"); s = s.Replace("\\/","/"); s = s.Replace("\\/","/"); textBox6.Text = s; //отправка файла на полученый сервер NameValueCollection nvc = new NameValueCollection(); //nvc.Add("user", "user"); //nvc.Add("passwd", "passwd"); string s9; s9 = HttpUploadFile(s, @"C:\file_1.jpg", "photo", "image/jpeg", nvc); textBox6.Text = s9; char[] delimiterChars = { ':', ',' }; string[] parameters = s9.Split(delimiterChars); string server = parameters[1]; char[] delimiterChars2={':'}; string[] parameters2 = s9.Split(delimiterChars2); string hash = parameters2[7]; char[] delimiterChars3 = { '"' }; string[] parameters3 = hash.Split(delimiterChars3); hash = parameters3[1]; string photo = s9.Substring(s9.IndexOf("photo")+8, s9.IndexOf("hash") - s9.IndexOf("photo")-11); photo = photo.Replace("\\\"", "\""); //сохранение фотографии на сервере string url3 = "https://api.vk.com/method/photos.saveWallPhoto?server=" + server + "&photo=" + HttpUtility.UrlEncode(photo) + "&hash=" + hash + "&access_token=" + textBox3.Text.Trim(); textBox6.Text = textBox6.Text + " ---------- " + url3; System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; System.Net.WebRequest post_request3 = System.Net.WebRequest.Create(url3); System.Net.WebResponse post_request_response3 = post_request3.GetResponse(); System.IO.Stream post_request_stream3 = post_request_response3.GetResponseStream(); System.IO.StreamReader post_request_stream_reader3 = new System.IO.StreamReader(post_request_stream3); string post_request_answer3 = post_request_stream_reader3.ReadToEnd(); textBox6.Text = textBox6.Text + " ---------- " + post_request_answer3; Код функции HttpUploadFile: public static string HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc) { Console.WriteLine(string.Format("Uploading {0} to {1}", file, url)); string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url); //wr.ContentType = "multipart/form-data; boundary=" + boundary; wr.ContentType = "multipart/form-data; boundary=" + boundary; wr.Method = "POST"; wr.KeepAlive = true; wr.Credentials = System.Net.CredentialCache.DefaultCredentials; Stream rs = wr.GetRequestStream(); string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; foreach (string key in nvc.Keys) { rs.Write(boundarybytes, 0, boundarybytes.Length); string formitem = string.Format(formdataTemplate, key, nvc[key]); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); rs.Write(formitembytes, 0, formitembytes.Length); } rs.Write(boundarybytes, 0, boundarybytes.Length); string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n"; string header = string.Format(headerTemplate, paramName, file, contentType); byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); rs.Write(headerbytes, 0, headerbytes.Length); FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { rs.Write(buffer, 0, bytesRead); } fileStream.Close(); byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); rs.Write(trailer, 0, trailer.Length); rs.Close(); WebResponse wresp = null; try { wresp = wr.GetResponse(); Stream stream2 = wresp.GetResponseStream(); StreamReader reader2 = new StreamReader(stream2); //Form Form1 = new Form1(); //Form //textBox6.Text = reader2.ReadToEnd(); //MessageBox.Show(s3); //Console.WriteLine(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd())); string s3 = reader2.ReadToEnd(); return s3; } catch (Exception ex) { Console.WriteLine("Error uploading file", ex); if (wresp != null) { wresp.Close(); wresp = null; } wresp = wr.GetResponse(); Stream stream2 = wresp.GetResponseStream(); StreamReader reader2 = new StreamReader(stream2); string s3 = reader2.ReadToEnd(); return s3; } finally { wr = null; } }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д