- [C#] Hướng dẫn fix lỗi Visual Studio 2022 not Support Target Net Framework 4.5.2
- [C#] Giới thiệu thư viện Sunny UI thiết kế giao diện trên Winform
- [DATABASE] Hướng dẫn thêm và cập nhật Extended Property Column trong Table Sqlserver
- [DEVEXPRESS] Hướng dẫn sử dụng Vertical Gridview để hiển thị thông tin sản phẩm
- [C#] Hướng dẫn sử dụng Json Schema để Validate chuỗi string có phải json
- [C#] Hướng dẫn sử dụng công cụ Clean Code trên Visual Studio
- [C#] Hướng dẫn Drag and Drop File vào RichTextBox
- [C#] Hướng dẫn tạo hiệu ứng Karaoke Text Effect Winform
- [C#] Sử dụng thư viện ZedGraph vẽ biểu đồ Line, Bar, Pie trên Winform
- [DATABASE] Hướng dẫn sort sắp xếp địa chỉ IP trên sqlserver sử dụng hàm PARSENAME
- [C#] Theo dõi sử kiện process Start hay Stop trên Winform
- [ASP.NET] Chia sẻ source code chụp hình sử dụng camera trên website
- [C#] Chạy ứng dụng trên Virtual Desktop (màn hình ảo) Winform
- [C#] Mã hóa và giải mã Data Protection API trên winform
- [C#] Hướng dẫn tạo Gradient Background trên Winform
- [DATABASE] Hướng dẫn convert Epoch to DateTime trong sqlserver
- [DATABASE] Hướng dẫn sử dụng STRING_AGG và CONCAT_WS trong sqlserver 2017
- [C#] Hướng dẫn Copy With All Property in Class Object
- [DEVEXPRESS] Hướng dẫn load Json DataSource vào GridView
- [C#] Hướng dẫn tạo chữ ký trên winform Signature Pad
[C#] Hướng dẫn thêm cookie vào Http Request website
Xin chào các bạn, bài viết hôm nay mình sẽ hướng dẫn các bạn cách tích hợp cookie vào HttpRequest trong lập trình C#.
Khi các bạn gởi Request để lấy dữ liệu từ website, một số trang web có yêu cầu cookie để trả Response về.
Vậy Cookie là gì?
Cookie là một đoạn văn bản mà một Web server có thể lưu trên ổ cứng của người dùng. Cookie cho phép một website lưu các thông tin trên máy tính của người dùng và sau đó lấy lại nó.
Các mẩu thông tin sẽ được lưu dưới dạng cặp tên – giá trị (name-value).
Mình ví dụ ở trang web http://batdongsan.com.vn
Giống như hình ở trên, các bạn sẽ thấy khi truy cập lấy thông tin mới nhất từ trang web batdongsan.com.vn, thì nó sẽ gởi theo cookie với tham số
Key: psortfilter và Value: 1%24all%24%2BAhRasUDZiQ64tRxy5UrOQ%3D%3D
Ở đường dẫn request trên mình request từ địa chỉ: https://batdongsan.com.vn/ban-can-ho-chung-cu-tp-hcm
Nếu mặc định chúng ta không gởi kèm thông tin Cookie thì nó trả về cho chúng ta dữ liệu là tin thông thường.
Vì vậy, khi request chúng ta cần gởi bộ cookie để dữ liệu server trả về đúng yêu cầu của mình.
Dưới đây là hình ảnh demo Request khi sử dụng cookie và không sử dụng cookie để các bạn tham khảo:
Source code Cookie Http Request C#:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace bds
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Task MakeAsyncRequest(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5";
Cookie cookie = new Cookie("psortfilter", txt_cookie.Text);
request.CookieContainer = new CookieContainer();
Uri uri = new Uri(url);
request.CookieContainer.Add(uri, cookie);
request.Method = WebRequestMethods.Http.Get;
request.Timeout = 20000;
request.Proxy = null;
Task task = Task.Factory.FromAsync(
request.BeginGetResponse,
asyncResult => request.EndGetResponse(asyncResult),
(object)null);
return task.ContinueWith(t => ReadStreamFromResponse(t.Result));
}
private static string ReadStreamFromResponse(WebResponse response)
{
using (Stream responseStream = response.GetResponseStream())
using (StreamReader sr = new StreamReader(responseStream))
{
string strContent = sr.ReadToEnd();
return strContent;
}
}
private void button1_Click(object sender, EventArgs e)
{
string http = "https://batdongsan.com.vn/ban-can-ho-chung-cu-tp-hcm";
string data = MakeAsyncRequest(http).Result;
richTextBox1.Text = data;
webBrowser1.DocumentText = data;
}
}
}
HAVE FUN :)