Search code examples
c#http-posttcpclient

http post using tcpclient in c# not working


Hi i am trying to post to login page using tcpclient class . but it says 302 error. same thing i can do using webclient. please suggest where i am missing something. i have already achieved using webclient class. but i have asked to do at lower level. please suggest.

i have tried following

 string sPost =  "POST  http://www.udupikrishnarestaurant.com/ HTTP/1.1\r\n"  +

 "Host: www.udupikrishnarestaurant.com\r\n" +

 "Connection: keep-alive\r\n" +

 "Content-Length: 632\r\n" +

 "Cache-Control: max-age=0\r\n" +

 "Origin: http://www.udupikrishnarestaurant.com \r\n" +

"Upgrade-Insecure-Requests: 1\r\n" +

"User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36 \r\n" +

"Content-Type: application/x-www-form-urlencoded\r\n" +

"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 \r\n" +

"Referer: http://www.udupikrishnarestaurant.com/ \r\n" +

"Accept-Encoding: gzip, deflate, br\r\n" +

"Accept-Language: en-US,en;q=0.8\r\n" +

"\r\n" +

"__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=/wEPDwUKLTM0ODY4NTA5Mg9kFgRmD2QWAgIBDxYCHgdWaXNpYmxlaGQCAQ8WAh4EVGV4dAUOMTgyLjY5LjEwOC4yMTFkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYCBQlidG5TdWJtaXQFCWJ0bkZvcmdvdCvBSicNzlFc1g4UTZeO96HhGK8T&__VIEWSTATEGENERATOR=CA0B0334&__EVENTVALIDATION=/wEdAAr0HIr+WBkxh8yUckvqwLD4LqRynaTFa/5Hs7sApa3/2aRDGrH080vTDzQFiILKSswLyPw09K59GBb2rr9Ouzg352npSE7sRexHKIcGFqd4MCl0Pj8zqX34hAcL3lPJ6TZjemWCTRgEB59HPczIGVNwdjb4xzpKucCqKjegIpvFhjzmltaUM7aEAN+g9cP/m13MQ92x/wmKgUDwu+2MEZnSA5KkNGEzQJYQmFWkBWmYqAdLpnM=&ddlFloor=2&txtUserName=test&txtPassword=1234&btnSubmit.x=15&btnSubmit.y=3";


byte[] buf = new byte[1024];
  string header = sPost;

  var client = new TcpClient();
  client.Connect("182.50.132.48", 80);

  // send request

  var stream = client.GetStream();
  var streamReader = new StreamReader(stream);
  var streamWriter = new StreamWriter(stream);

  streamWriter.Write(header);
  streamWriter.Flush();
  stream.Flush();

  // get response

  var response1 = streamReader.ReadLine();

Solution

  • 302 is not an error. It is a request for redirection - the form tells you "go there instead", most likely as a result of your login attempt. WebClient handles the redirection, your client doesn't.

    There's a lot of HTTP to implement. Unless this is purely an excercise, don't try to write your own HTTP client. Redirection is just the top of the iceberg.