Skip to content

Commit

Permalink
HttpMessageHandler
Browse files Browse the repository at this point in the history
  • Loading branch information
XuanThuLab committed Aug 22, 2020
1 parent a4a4257 commit acc0655
Show file tree
Hide file tree
Showing 4 changed files with 161 additions and 0 deletions.
27 changes: 27 additions & 0 deletions CS029_Networking/4.HttpMessageHandler/.vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/bin/Debug/netcoreapp2.1/HttpClientExample.dll",
"args": [],
"cwd": "${workspaceFolder}",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
"console": "internalConsole",
"stopAtEntry": false
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
]
}
42 changes: 42 additions & 0 deletions CS029_Networking/4.HttpMessageHandler/.vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/HttpClientExample.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"${workspaceFolder}/HttpClientExample.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"${workspaceFolder}/HttpClientExample.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
}
]
}
12 changes: 12 additions & 0 deletions CS029_Networking/4.HttpMessageHandler/HttpClientExample.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="System.Text.Encoding.CodePages" Version="4.5.1" />
</ItemGroup>

</Project>
80 changes: 80 additions & 0 deletions CS029_Networking/4.HttpMessageHandler/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
namespace HttpClientHandlerExample {

class Program {
static CookieContainer cookieContainer = new CookieContainer (); // Sử dụng CookieContainer riêng, để lưu lại Cookie - hoặc thêm cookie

//nested class - MyHttpClientHandler
public class MyHttpClientHandler : HttpClientHandler {

// Khởi tạo và thiết lập cho handler
public MyHttpClientHandler (CookieContainer cookie_container) {

CookieContainer = cookie_container; // Thay thế CookieContainer mặc định
AllowAutoRedirect = false; // không cho tự động Redirect
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; // Chấp nhận nén dữ liệu
UseCookies = true;
}

// Nạp chồng SendAsync
protected override async Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, CancellationToken cancellationToken) {
ShowHeaders ("Request header trước khi qua Handler ", request.Headers);

var task = base.SendAsync (request, cancellationToken); // gọi SendAsync của lớp cơ sở (bắt buộc)
await task;

ShowHeaders ("Request header sau khi qua Handler ", request.Headers);

// Xem Cookie nếu có
// var uri = request.RequestUri;
// var cookieHeader = CookieContainer.GetCookieHeader(uri);
// Console.WriteLine(cookieHeader);

return task.Result;
}
}

// In thông tin Header
public static void ShowHeaders (string lable, HttpHeaders headers) {
Console.WriteLine (lable);
foreach (var header in headers) {
string value = string.Join (" ", header.Value);
Console.WriteLine ($"{header.Key,20} : {value}");
}
Console.WriteLine ();

}

public static async Task<string> GetWebContent (string url) {
using (var myHttpClientHandler = new MyHttpClientHandler (cookieContainer))
using (var httpClient = new HttpClient (myHttpClientHandler)) {

Console.WriteLine ($"Starting connect {url}");
httpClient.DefaultRequestHeaders.Add ("Accept", "text/html,application/xhtml+xml+json");
httpClient.DefaultRequestHeaders.Add ("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36");
HttpResponseMessage response = await httpClient.GetAsync (url);

response.EnsureSuccessStatusCode ();
string htmltext = await response.Content.ReadAsStringAsync ();
return htmltext;
}
}

static void Main (string[] args) {
string url = "https://www.google.com.vn/";

cookieContainer.Add (new Uri (url), new Cookie ("NameCookie", "ValueCookie")); // Thêm Cookie khi gửi Requests

var htmltask = GetWebContent (url);
htmltask.Wait (); // cho hoàn thành tác vụ
var html = htmltask.Result; // đọc chuỗi trả về (content)
Console.WriteLine (html != null ? html.Substring (0, 150) : "Lỗi");
}

}
}

0 comments on commit acc0655

Please sign in to comment.