Skip to content

Commit

Permalink
HttpCLient Example - Merge branch 'cs029' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
XuanThuLab committed Aug 21, 2020
2 parents 9ce4dad + 9204e10 commit 20c67b1
Show file tree
Hide file tree
Showing 5 changed files with 160 additions and 0 deletions.
27 changes: 27 additions & 0 deletions CS023_Networking/1.HttpClientExample/.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 CS023_Networking/1.HttpClientExample/.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"
}
]
}
8 changes: 8 additions & 0 deletions CS023_Networking/1.HttpClientExample/HttpClientExample.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">

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

</Project>
78 changes: 78 additions & 0 deletions CS023_Networking/1.HttpClientExample/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace HttpClientExample
{

class Program
{
/// In ra thông tin các Header của HTTP Response
public static void ShowHeaders(HttpHeaders headers)
{
Console.WriteLine("Các Header:");
foreach (var header in headers)
{
string value = string.Join(" ", header.Value);
Console.WriteLine($"{header.Key,20} : {value}");
}
Console.WriteLine();
}

// Tải về và hiện thị thông tin trang tải về,
// url là địa chỉ cần tải ví dụ: https://google.com.vn
public static async Task<string> GetWebContent(string url)
{
using (var httpClient = new HttpClient())
{
Console.WriteLine($"Starting connect {url}");
try {
// Thêm header vào HTTP Request
httpClient.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml+json");
HttpResponseMessage response = await httpClient.GetAsync(url);

// Phát sinh Exception nếu mã trạng thái trả về là lỗi
response.EnsureSuccessStatusCode();

if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Tải thành công - statusCode {(int)response.StatusCode} {response.ReasonPhrase}");
// Đọc thông tin header trả về
ShowHeaders(response.Headers);


Console.WriteLine("Starting read data");

// Đọc nội dung content trả về
string htmltext = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Nhận được {htmltext.Length} ký tự");
Console.WriteLine();
return htmltext;
}
else
{
Console.WriteLine($"Lỗi - statusCode {response.StatusCode} {response.ReasonPhrase}");
return null;
}
} catch (Exception e) {
Console.WriteLine(e.Message);
return null;
}
}
}
static void Main(string[] args)
{
var htmltask = GetWebContent("https://google.com.vn");
htmltask.Wait(); // Chờ tải xong
// Hoặc wait htmltask; nếu chuyển Main thành async

var html = htmltask.Result;
Console.WriteLine(html!=null ? html.Substring(0, 255): "Lỗi");
}
}
}
5 changes: 5 additions & 0 deletions CS023_Networking/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Ví dụ về Networking trong C#
https://xuanthulab.net/networking-su-dung-httpclient-trong-c-tao-cac-truy-van-http.html
https://xuanthulab.net/networking-su-dung-httpmessagehandler-cho-httpclient-trong-c-csharp.html
https://xuanthulab.net/networking-su-dung-lop-httplistener-trong-c-de-tao-may-chu-web-http-don-gian.html
https://xuanthulab.net/networking-giao-thuc-tcp-voi-cac-lop-tcplistener-tcpclient-va-cac-lop-uri-ipaddress-c-c-sharp.html

0 comments on commit 20c67b1

Please sign in to comment.