17

Thanks icktoofay, I tried using HttpWebRequest and HttpWebResponse.

When I request for URL by passing the Credentials like UserName And Password.

I will get the Session Id Back in the Response.

After getting that Session Id, How to Move Further.

The authenticated user are tracked using credentials/cookies. I'm Having the Exact Url of the File to be downloaded and credentials. If you want to use Cookies I will. I need to read the File Data and write/save it in a Specified Location.

The code I'm using is;

string username = "";
string password = "";
string reqString = "https://xxxx.com?FileNAme=asfhasf.mro" + "?" + 
             "username=" + username + &password=" + password;
byte[] requestData = Encoding.UTF8.GetBytes(reqString);
string s1;
CookieContainer cc = new CookieContainer();

var request = (HttpWebRequest)WebRequest.Create(loginUri);
request.Proxy = null;
request.CookieContainer = cc;
request.Method = "POST";
HttpWebResponse ws = (HttpWebResponse)request.GetResponse();
Stream str = ws.GetResponseStream();
//ws.Cookies
//var request1 = (HttpWebRequest)WebRequest.Create(loginUri);
 byte[] inBuf = new byte[100000];
int bytesToRead = (int) inBuf.Length;
int bytesRead = 0;
while (bytesToRead > 0) 
{
    int n = str.Read(inBuf, bytesRead,bytesToRead);
    if (n==0)
    break;
    bytesRead += n;
    bytesToRead -= n;
}
FileStream fstr = new FileStream("weather.jpg", FileMode.OpenOrCreate, 
                                     FileAccess.Write);
fstr.Write(inBuf, 0, bytesRead);
str.Close();
fstr.Close();
0

2 Answers 2

20

This is how I do it:

const string baseurl = "http://www.some......thing.com/";
CookieContainer cookie;

The first method logins to web server and gets session id:

public Method1(string user, string password) {
  HttpWebRequest req = (HttpWebRequest)WebRequest.Create(baseurl);

  req.Method = "POST";
  req.ContentType = "application/x-www-form-urlencoded";
  string login = string.Format("go=&Fuser={0}&Fpass={1}", user, password);
  byte[] postbuf = Encoding.ASCII.GetBytes(login);
  req.ContentLength = postbuf.Length;
  Stream rs = req.GetRequestStream();
  rs.Write(postbuf,0,postbuf.Length);
  rs.Close();

  cookie = req.CookieContainer = new CookieContainer();

  WebResponse resp = req.GetResponse();
  resp.Close();
}

The other method gets the file from server:

string GetPage(string path) {
  HttpWebRequest req = (HttpWebRequest)WebRequest.Create(path);
  req.CookieContainer = cookie;
  WebResponse resp = req.GetResponse();
  string t = new StreamReader(resp.GetResponseStream(), Encoding.Default).ReadToEnd();
  return IsoToWin1250(t);
}

Note that I return the page as string. You would probably better return it as bytes[] to save to disk. If your jpeg files are small (they usually are not gigabyte in size), you can simply put them to memory stream, and then save to disk. It will take some 2 or 3 simple lines in C#, and not 30 lines of tough code with potential dangerous memory leaks like you provided above.

3
  • Thanks Ales, Yes, I tried the First Method and Got the Cookie as Session Id and When I assign that Cookie Collection to the New WebRequest and Try Requesting to the File URL i.e.ghasghfh/filename=hasfhgfhg.mro. When I try getting the Response in the String Form. The String Values that I get is the HTML code/ViewSource of Login Page. Please Reply me.. I really Appreciate ur Help.
    – Vinay
    Commented Jan 16, 2011 at 10:25
  • It means that you did a successful download of web page, but haven't passed login and password correctly. My example (see the line with string.Format command) uses a format of POST, which I saw on the server with php where I wanted to use my code. I started with Firefox plugin which shows all communication with server, and then did the same in my code. And it works.
    – Al Kepp
    Commented Jan 16, 2011 at 10:31
  • Al Kepp, U r right, I'm able to download the HTML of the file successfully. any suggestions where the issue/problem persists in. Is there any extra care to be taken.
    – Vinay
    Commented Jan 17, 2011 at 7:29
2
public override DownloadItems GetItemStream(string itemID, object config = null, string downloadURL = null, string filePath = null, string)
    {
        DownloadItems downloadItems = new DownloadItems();
        try
        {
            if (!string.IsNullOrEmpty(filePath))
            {
                using (FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write))
                {
                    if (!string.IsNullOrEmpty(downloadURL))
                    {
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(downloadURL);
                        request.Method = WebRequestMethods.Http.Get;
                        request.PreAuthenticate = true;
                        request.UseDefaultCredentials = true;
                        const int BUFFER_SIZE = 16 * 1024;
                        {
                            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                            {
                                using (var responseStream = response.GetResponseStream())
                                {
                                    var buffer = new byte[BUFFER_SIZE];
                                    int bytesRead;
                                    do
                                    {
                                        bytesRead = responseStream.Read(buffer, 0, BUFFER_SIZE);
                                        fileStream.Write(buffer, 0, bytesRead);
                                    } while (bytesRead > 0);
                                }
                            }
                            fileStream.Close();
                            downloadItems.IsSuccess = true;
                        }
                    }
                    else
                        downloadItems.IsSuccess = false;
                }
            }
        }
        catch (Exception ex)
        {
            downloadItems.IsSuccess = false;
            downloadItems.Exception = ex;
        }
        return downloadItems;
    }
2
  • In this way, the user is able to download using HttpWebRequest.
    – anju singh
    Commented Oct 1, 2019 at 12:16
  • 2
    You should add an explanation for your answer, or explain what this answer improves over the existing, upvoted one in this 8 year old question.
    – skolldev
    Commented Oct 1, 2019 at 12:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.