CÁC GIẢI PHÁP LẬP TRÌNH C# - Trang 439

439

Chương 11: Lập trình mạng

public class DownloadForm : System.Windows.Forms.Form {

private System.Windows.Forms.PictureBox picBox;

private System.Windows.Forms.TextBox textBox;

// (Bỏ qua phần mã designer.)

private void DownloadForm_Load(object sender, System.EventArgs e) {

string picUri =

"http://localhost/winXP.gif";

string htmlUri =

"http://localhost/iishelp/iis/misc/default.asp";

// Tạo yêu cầu.

WebRequest requestPic = WebRequest.Create(picUri);

WebRequest requestHtml = WebRequest.Create(htmlUri);

// Nhận đáp ứng. Công việc này sẽ mất nhiều

// thời gian, đặc biệt khi file cần lấy quá lớn.

WebResponse responsePic = requestPic.GetResponse();

WebResponse responseHtml = requestHtml.GetResponse();

// Đọc response stream.

Image downloadedImage =

Image.FromStream(responsePic.GetResponseStream());

StreamReader r =

new StreamReader(responseHtml.GetResponseStream());

string htmlContent = r.ReadToEnd();

r.Close();

// Hiển thị ảnh.

picBox.Image = downloadedImage;

// Hiển thị nội dung dạng text của trang HTML.

textBox.Text = htmlContent;

}

}