Post запрос в ВК

Scorpio2011

Client
Регистрация
07.02.2015
Сообщения
104
Благодарностей
18
Баллы
18
Ребята подскажи пожалуйста что тут не так?
Код:
            //отправка файла на полученый сервер
            NameValueCollection nvc = new NameValueCollection();
            //nvc.Add("user", "[email protected]");
            //nvc.Add("passwd", "dfvgbh2010");
            string s9;
            s9 = HttpUploadFile(s, @"C:\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.save?server=" + server + "&photo=" + HttpUtility.UrlEncode(photo) + "&hash=" + hash + "&access_token=99829779&access_token=ab8eae8a589a654c96d48e67672348143d7b60adb878f0a93bb7f69c7aed245d820ed11622d72e109b29c";
            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;
        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;
            }
    
    
        }
Знаний в c# у меня только поверхностные, нашел тут скрипт (http://pastebin.com/y8njpFFz) на C# но он не запускается в зеннке выдает три ошибки


Или этот вариант

Код:
//string upload_url = "полученная строка в GetUploadUrl";
//byte[] pic = картинка (из файла или же перевод из Image
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(upload_url);
Stream _stream;
string _boundary = String.Format("--{0}", GetMD5());
string _templateFile = "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n";
string _templateEnd = "--{0}--\r\n\r\n";
Request.Method = "POST";
Request.ContentType = String.Format("multipart/form-data; boundary={0}", _boundary);
_stream = Request.GetRequestStream();
string FilePath = "test.jpg";
string FileType = "application/octet-stream";
string Name = "file1";
byte[] contentFile = Encoding.UTF8.GetBytes(String.Format(_templateFile, _boundary, Name, FilePath, FileType));
_stream.Write(contentFile, 0, contentFile.Length);
_stream.Write(pic, 0, pic.Length);
byte[] _lineFeed = Encoding.UTF8.GetBytes("\r\n");
_stream.Write(_lineFeed, 0, _lineFeed.Length);
byte[] contentEnd = Encoding.UTF8.GetBytes(String.Format(_templateEnd, _boundary));
_stream.Write(contentEnd, 0, contentEnd.Length);
HttpWebResponse webResponse = (HttpWebResponse)Request.GetResponse();
StreamReader read = new StreamReader(webResponse.GetResponseStream());
return read.ReadToEnd();
Или этот вариант нашел вот тут http://www.cyberforum.ru/csharp-net/thread304372.html
 
Последнее редактирование:

Кто просматривает тему: (Всего: 1, Пользователи: 0, Гости: 1)