1 Replies - 3264 Views - Last Post: 17 February 2013 - 07:05 AM Rate Topic: -----

#1 delphi5  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 16-February 13

how to log in to a website and get data from that website

Posted 17 February 2013 - 06:22 AM

dear all
I'm beginner at c#
for a project i need to [log on] to a website using an username and password and get some variable data
data in this website changed every 15 minutes
at all i need to list all data in grid and other components int this page
i fount that i must have 2 classes for this reason
using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.IO;
 
namespace BaseClassNameSpace.Web.BaseServices
{
/// <summary>
///This base class provides implementation of request 
///and response methods during Http Calls.
/// </summary>
  
      public class HttpBaseClass
      {
 
            private string UserName;
            private string UserPwd;
            private string ProxyServer;
            private int ProxyPort;
            private string Request;
            
            public HttpBaseClass(string HttpUserName, 
              string HttpUserPwd, string HttpProxyServer, 
              int HttpProxyPort, string HttpRequest)
            {
                  UserName = HttpUserName;
                  UserPwd = HttpUserPwd;
                  ProxyServer = HttpProxyServer;
                  ProxyPort = HttpProxyPort;
                  Request = HttpRequest;
            }
 
/// <summary>
/// This method creates secure/non secure web
/// request based on the parameters passed.
/// </summary>
/// <param name="uri"></param>
/// <param name="collHeader">This parameter of type
///    NameValueCollection may contain any extra header
///    elements to be included in this request      </param>
/// <param name="RequestMethod">Value can POST OR GET</param>
/// <param name="NwCred">In case of secure request this would be true</param>
/// <returns></returns>
            public virtual HttpWebRequest CreateWebRequest(string uri, 
              NameValueCollection collHeader, 
              string RequestMethod, bool NwCred)
            {
                  HttpWebRequest webrequest = 
                   (HttpWebRequest) WebRequest.Create(uri);
                  webrequest.KeepAlive = false;
                  webrequest.Method = RequestMethod;
 
                  int iCount = collHeader.Count;
                  string key;
                  string keyvalue;
 
                  for (int i=0; i < iCount; i++)
                  {
                        key = collHeader.Keys[i];
                        keyvalue = collHeader[i];
                        webrequest.Headers.Add(key, keyvalue);
                  }
                  
                  webrequest.ContentType = "text/html"; 
                  //"application/x-www-form-urlencoded";
 
                  if (ProxyServer.Length > 0)
                  {
                     webrequest.Proxy = new 
                      WebProxy(ProxyServer,ProxyPort);
                  }
                  webrequest.AllowAutoRedirect = false;
 
                  if (NwCred)
                  {
                      CredentialCache wrCache = 
                              new CredentialCache();
                      wrCache.Add(new Uri(uri),"Basic",
                        new NetworkCredential(UserName,UserPwd));
                      webrequest.Credentials = wrCache;
                  }
                  //Remove collection elements
                  collHeader.Clear();
                  return webrequest;
            }//End of secure CreateWebRequest
            
            /// <summary>
            /// This method retreives redirected URL from
            /// response header and also passes back
            /// any cookie (if there is any)
            /// </summary>
            /// <param name="webresponse"></param>
            /// <param name="Cookie"></param>
            /// <returns></returns>
            public virtual string GetRedirectURL(HttpWebResponse 
                 webresponse, ref string Cookie)
            {
                  string uri="";
 
                  WebHeaderCollection headers = webresponse.Headers;
                  
                  if ((webresponse.StatusCode == HttpStatusCode.Found) || 
                    (webresponse.StatusCode == HttpStatusCode.Redirect) ||
                    (webresponse.StatusCode == HttpStatusCode.Moved) ||
                    (webresponse.StatusCode == HttpStatusCode.MovedPermanently))
                  {
                        // Get redirected uri
                        uri = headers["Location"] ;
                        uri = uri.Trim();
                  }
 
                  //Check for any cookies
                  if (headers["Set-Cookie"] != null)
                  {
                        Cookie = headers["Set-Cookie"];  
                  }
                  //                string StartURI = "http:/";
//                if (uri.Length > 0 && uri.StartsWith(StartURI)==false)
//                {
//                      uri = StartURI + uri;
//                }
                  return uri;
            }//End of GetRedirectURL method
 
 
            public virtual string GetFinalResponse(string ReUri, 
             string Cookie, string RequestMethod, bool NwCred)
            {
                  NameValueCollection collHeader = 
                        new NameValueCollection();
 
                  if (Cookie.Length > 0)
                  {
                        collHeader.Add("Cookie",Cookie);
                  }
 
                  HttpWebRequest webrequest = 
                    CreateWebRequest(ReUri,collHeader, 
                    RequestMethod, NwCred);
                        
                  BuildReqStream(ref webrequest);
 
                  HttpWebResponse webresponse;
 
                  webresponse = (HttpWebResponse)webrequest.GetResponse();
 
                  Encoding enc = System.Text.Encoding.GetEncoding(1252);
                  StreamReader loResponseStream = new 
                    StreamReader(webresponse.GetResponseStream(),enc);
 
                  string Response = loResponseStream.ReadToEnd();
 
                  loResponseStream.Close();
                  webresponse.Close();
                  
                  return Response;
            }
 
            private void BuildReqStream(ref HttpWebRequest webrequest)
                  //This method build the request stream for WebRequest
            {
                  byte[] bytes = Encoding.ASCII.GetBytes(Request);
                  webrequest.ContentLength=bytes.Length;
 
                  Stream oStreamOut = webrequest.GetRequestStream();
                  oStreamOut.Write(bytes,0,bytes.Length);
                  oStreamOut.Close();
            }
      }
}//End of HttpBaseClass class




using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.IO;
using BaseClassNameSpace.Web.BaseServices;
 
namespace DeriveClassNameSpace.Services.Web
{
 
      public class HttpRequestResponse
      {
            private string URI;
            private string Request;
            private string UserName;
            private string UserPwd;
            private string ProxyServer;
            private int ProxyPort;
            private string RequestMethod = "GET";
 
            public HttpRequestResponse(string pRequest, 
                                 string pURI)//Constructor
            {
                  Request = pRequest;
                  URI = pURI;
            }
            
            public string HTTP_USER_NAME
            {
                  get 
                  {
                        return UserName; 
                  }
                  set 
                  {
                        UserName = value; 
                  }
            }

            public string HTTP_USER_PASSWORD
            {
                  get 
                  {
                        return UserPwd; 
                  }
                  set 
                  {
                        UserPwd = value; 
                  }
            }
 
            public string PROXY_SERVER
            {
                  get 
                  {
                        return ProxyServer; 
                  }
                  set 
                  {
                        ProxyServer = value; 
                  }
            }
 
            public int PROXY_PORT
            {
                  get 
                  {
                        return ProxyPort; 
                  }
                  set 
                  {
                        ProxyPort = value; 
                  }
            }
 
            public string SendRequest()
            /*This public interface receives the request 
            and send the response of type string. */
            {
              string FinalResponse="";
              string Cookie="";
 
              NameValueCollection collHeader = new NameValueCollection();

              HttpWebResponse webresponse;
 
              HttpBaseClass BaseHttp =  new 
                HttpBaseClass(UserName,UserPwd,
                ProxyServer,ProxyPort,Request);
              try
              {
                HttpWebRequest webrequest = 
                  BaseHttp.CreateWebRequest(URI, 
                  collHeader, RequestMethod, true);
                webresponse = 
                 (HttpWebResponse)webrequest.GetResponse();
 
                string ReUri = 
                  BaseHttp.GetRedirectURL(webresponse,
                  ref Cookie);
                //Check if there is any redirected URI.
                webresponse.Close();
                ReUri = ReUri.Trim();
                if (ReUri.Length == 0) //No redirection URI
                {
                  ReUri = URI;
                }
                RequestMethod="POST";
                FinalResponse = BaseHttp.GetFinalResponse(ReUri, 
                                   Cookie, RequestMethod, true);
 
              }//End of Try Block
 
              catch (WebException e)
              {
                 throw CatchHttpExceptions(FinalResponse = e.Message);
              }
              catch (System.Exception e)
              {
                 throw new Exception(FinalResponse = e.Message);
              }
              finally
              {
                 BaseHttp=null;
              }
              return FinalResponse;
            } //End of SendRequestTo method
 
            private WebException CatchHttpExceptions(string ErrMsg)
            {
              ErrMsg = "Error During Web Interface. Error is: "+ErrMsg ;
              return new WebException(ErrMsg);
            }
      }//End of RequestResponse Class
}


now i dont know how to send request and get data from a website in my windows application


somebody can help me

Is This A Good Question/Topic? 0
  • +

Replies To: how to log in to a website and get data from that website

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5529
  • View blog
  • Posts: 11,843
  • Joined: 02-June 10

Re: how to log in to a website and get data from that website

Posted 17 February 2013 - 07:05 AM

Q:... how to do x,y,z with a database {probably for the first time}...
A: Read this tutorial
Entire section of tutorials
Parameterizing Your SQL Queries: The RIGHT Way To Query A Database.
Using SqlDependency to monitor SQL database changes
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1