POST запрос, нужен наглядный пример - C#
Формулировка задачи:
Весь день сижу и читаю тысячи тем про пост запросы, так и не увидел вообще ни одного ответа где бы было хоть какое то описание как собрать пост запрос. То что все копипастят с других сайтов шаблоны без данных вообще ниочем не говорят, так как не понятно что в какие параметры подставлять и самое главное непонятно пост запрос вообще отправлен или нет, тоесть сервер принял его или нет?
вот что видит фидлер, это пример на первой попавшейся ссылке
вот примеры с миллионов сайтов и форумов
какой из этих примеров является подходящим для моей задачи.
Главное чтобы в запросе были куки, я так понимаю судя по запросу...
Ткните пальцем какой нужен, а как заполнить попробую сам разобраться или другую тему создам с вопросом...
Листинг программы
- POST http://www.avito.ru/items/abuse/ufa_kvartiry_3-k_kvartira_65_m_257979174 HTTP/1.1
- Host: www.avito.ru
- User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0
- Accept: */*
- Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3
- Accept-Encoding: gzip, deflate
- Content-Type: application/x-www-form-urlencoded; charset=UTF-8
- X-Requested-With: XMLHttpRequest
- Referer: http://www.avito.ru/ufa/kvartiry/3-k_kvartira_65_m_257979174
- Content-Length: 9
- Cookie: sessid=2de03c2aa3473307ab8ac2d47494e6ce.1387952223; u=1oa81chz.q4jzgn.ebvxb00ltc; __gads=ID=ccef62ea2ae4d5a5:T=1387952224:S=ALNI_Mbg_CJMvOSWF0bqAZy_IVcCcAG0kg; __utma=99926606.1454440257.1387952231.1387952231.1387959783.2; __utmz=99926606.1387952231.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); v=1387959777; __utmb=99926606.9.9.1387959816357; __utmc=99926606; avito_ef_contacter=1
- Connection: keep-alive
- Pragma: no-cache
- Cache-Control: no-cache
- typeId=71
- HTTP/1.1 200 OK
- Server: nginx
- Date: Wed, 25 Dec 2013 08:20:59 GMT
- Content-Type: application/json; charset=utf-8
- Transfer-Encoding: chunked
- Connection: keep-alive
- Keep-Alive: timeout=15
- Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
- Set-Cookie: v=1387959777; expires=Wed, 25-Dec-2013 08:53:41 GMT; Max-Age=1800; path=/; domain=.avito.ru
- Content-Encoding: gzip
- X-Frame-Options: SAMEORIGIN
- 1a
- ‹ SJЙПKU jт{
- 0
Листинг программы
- HttpWebRequest r =
- WebRequest.Create("http://localhost:50781/AdvWksSalesS.svc/Address")
- as HttpWebRequest;
- DateTime creationDate = DateTime.Now;
- // Convert the date to JSON format.
- long ticks = (creationDate.ToUniversalTime().Ticks -
- (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks) / 10000;
- Int32 stateProvinceId = 79;
- Guid rowGuid = Guid.NewGuid();
- // __metadata is only required if inheritance is used.
- string requestPayload = "{__metadata:{Uri:'/Address/', " +
- "Type:'AdventureWorksModel.Address'}, " +
- "AddressLine1:'703 NW 170th St.', " +
- "City:'Kirkland', StateProvinceID:" +
- stateProvinceId.ToString() +
- ", PostalCode:'98021', rowguid:'" +
- rowGuid.ToString() +
- "', ModifiedDate:'\\/Date(" + ticks + ")\\/'}";
- r.Method = "POST";
- UTF8Encoding encoding = new UTF8Encoding();
- r.ContentLength = encoding.GetByteCount(requestPayload);
- r.Credentials = CredentialCache.DefaultCredentials;
- r.Accept = "application/json";
- r.ContentType = "application/json";
- //Write the payload to the request body.
- using ( Stream requestStream = r.GetRequestStream())
- {
- requestStream.Write(encoding.GetBytes(requestPayload), 0,
- encoding.GetByteCount(requestPayload));
- }
- try
- {
- HttpWebResponse response = r.GetResponse() as HttpWebResponse;
- string responseBody = "";
- using (Stream rspStm = response.GetResponseStream())
- {
- using (StreamReader reader = new StreamReader(rspStm))
- {
- textBoxResponse.Text = textBoxResponse.Text +
- "Response Description: " + response.StatusDescription;
- textBoxResponse.Text = textBoxResponse.Text +
- "Response Status Code: " + response.StatusCode;
- textBoxResponse.Text = textBoxResponse.Text + "\r\n\r\n";
- responseBody = reader.ReadToEnd();
- }
- }
- textBoxResponse.Text = "Success: " + response.StatusCode.ToString();
- }
- catch (System.Net.WebException ex)
- {
- textBoxResponse.Text = textBoxResponse.Text +
- "Exception message: " + ex.Message;
- textBoxResponse.Text = textBoxResponse.Text +
- "\r\nResponse Status Code: " + ex.Status;
- textBoxResponse.Text = textBoxResponse.Text + "\r\n\r\n";
- // get error details sent from the server
- StreamReader reader = new StreamReader(ex.Response.GetResponseStream());
- textBoxResponse.Text = textBoxResponse.Text + reader.ReadToEnd();
- }
Листинг программы
- using System;
- using System.IO;
- using System.Net;
- using System.Text;
- namespace Examples.System.Net
- {
- public class WebRequestPostExample
- {
- public static void Main ()
- {
- WebRequest request = WebRequest.Create ("http://www.contoso.com/PostAccepter.aspx ");
- request.Method = "POST";
- string postData = "This is a test that posts this string to a Web server.";
- byte[] byteArray = Encoding.UTF8.GetBytes (postData);
- request.ContentType = "application/x-www-form-urlencoded";
- request.ContentLength = byteArray.Length;
- Stream dataStream = request.GetRequestStream ();
- dataStream.Write (byteArray, 0, byteArray.Length);
- dataStream.Close ();
- WebResponse response = request.GetResponse ();
- Console.WriteLine (((HttpWebResponse)response).StatusDescription);
- dataStream = response.GetResponseStream ();
- StreamReader reader = new StreamReader (dataStream);
- string responseFromServer = reader.ReadToEnd ();
- Console.WriteLine (responseFromServer);
- reader.Close ();
- dataStream.Close ();
- response.Close ();
- }
- }
- }
Листинг программы
- public static HttpWebResponse PostMethod(string postedData, string postUrl)
- {
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
- request.Method = "POST";
- request.Credentials = CredentialCache.DefaultCredentials;
- UTF8Encoding encoding = new UTF8Encoding();
- var bytes = encoding.GetBytes(postedData);
- request.ContentType = "application/x-www-form-urlencoded";
- request.ContentLength = bytes.Length;
- using (var newStream = request.GetRequestStream())
- {
- newStream.Write(bytes, 0, bytes.Length);
- newStream.Close();
- }
- return (HttpWebResponse)request.GetResponse();
- }
Решение задачи: «POST запрос, нужен наглядный пример»
textual
Листинг программы
- POST http://www.avito.ru/items/abuse/1-k_kvartira_38_m_79_et._258104498 HTTP/1.1
- Content-Type: application/x-www-form-urlencoded;
- Host: www.avito.ru
- Content-Length: 9
- Expect: 100-continue
- Connection: Keep-Alive
- typeId=71
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д