Sunday, May 29, 2011

Login to a website and download file using C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Configuration;
using System.IO;

namespace HttpBrowsing
{
class SimulateHttp
{
private HttpWebRequest request;
private CookieContainer cookieContainer = new CookieContainer();

public bool doLogin(string uid, string pwd, string url)
{
// Create a request using a URL that can receive a post.
request = (HttpWebRequest)HttpWebRequest.Create(url);
request.CookieContainer = cookieContainer;

// Set the Method property of the request to POST.
request.Method = "POST";

// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";

// Create POST data and convert it to a byte array.
string postData = "user_name=" + uid + "&user_password=" + pwd;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);

// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
request.KeepAlive = true;

// Get the request stream.
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
response.Close();
return true;

}

public void downloadFile(string url, string fileName)
{
// Create a request using a URL that can receive a post.
request = (HttpWebRequest)HttpWebRequest.Create(url);
request.CookieContainer = cookieContainer;

// Set the Method property of the request to GET.
request.Method = "GET";

// Get the response.
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
using (StreamWriter writer = new StreamWriter(fileName, false))
{
writer.Write(reader.ReadToEnd());
writer.Flush();
writer.Close();
}
}
responseStream.Close();
}
response.Close();
}
}

public void doLogout(string url)
{
// Create a request using a URL that can receive a post.
request = (HttpWebRequest)HttpWebRequest.Create(url);
request.CookieContainer = cookieContainer;

// Set the Method property of the request to POST.
request.Method = "GET";

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Close();
}

}

1 comment:

Unknown said...

How do I tailor this for a specific webpage extraction?

Related Posts Plugin for WordPress, Blogger...