개발꿈나무
[C# 교과서] 37. C# 확장 기능(12) - 네트워크 프로그래밍 본문
반응형
네트워크 프로그래밍
C#에서 다루는 데이터는 인메모리, 파일, XML과 JSON을 포함하여 여러 데이터를 인터넷 같은 네트워크를 통해 주고받을 수 있다.
HttpClient 클래스로 웹 데이터 가져오기
닷넷에서 제공하는 HttpClient 클래스를 사용하면 인터넷에 견결된 네트워크상의 데이터를 가져오거나 전송할 수 있다.
using System;
using System.Net.Http;
using System.Threading.Tasks;
class HttpClientDemo
{
static async Task Main()
{
//[1] HttpClient 개체 생성
HttpClient httpClient = new HttpClient();
//[2] GetAsync() 메서드 호출
HttpResponseMessage httpResponseMessage =
await httpClient.GetAsync("https://hyokye0ng.tistory.com/");
//[3] HTML 가져오기
string responseBody = await httpResponseMessage.Content.ReadAsStringAsync();
//[4] 출력
Console.WriteLine(responseBody);
}
}
https://hyokye0ng.tistory.com/ 웹사이트의 HTML 문서를 읽어 콘솔에 출력한다.
HTML로 내려받은 문자열은 웹 브라우저 같은 프로그램에서는 HTML을 실행해서 보여주지만 위 코드에서는 텍스트로 화면에 출력한다.
GetAsync()와 PostAsync() 메서드
GetAsync() 메서드는 URL에서 데이터를 가져오고, PostAsync() 메서드는 해당 URL로 데이터를 전송한다.
using System;
using System.Net;
using System.Threading;
class WebClientDemo
{
static void Main()
{
WebClient client = new WebClient();
// 동기적으로 출력
string google = client.DownloadString("http://www.google.co.kr");
Console.WriteLine("Google: " + google.Substring(0, 10)); // 10자만 가져오기
string naver = client.DownloadString(new Uri("http://www.naver.com"));
Console.WriteLine("Naver: " + naver.Substring(0, 10));
// 비동기적으로 출력
client.DownloadStringAsync(new Uri("https://hyokye0ng.tistory.com/"));
client.DownloadStringCompleted += Client_DownloadStringCompleted;
Thread.Sleep(3000); // 잠시 대기
}
private static void Client_DownloadStringCompleted(object sender,
DownloadStringCompletedEventArgs e)
{
string r = e.Result.Replace("\n", "").Substring(0, 10);
Console.WriteLine($"DotNetKorea: {r}");
}
}
HttpWebRequest 클래스를 사용하여 웹 페이지 가져오기
using System;
using System.IO;
using System.Net;
class HttpWebRequestDemo
{
static void Main()
{
// 아래 URL에서 HTML문서를 가져올 수 있다고 가정
string url = "http://www.google.com";
var req = HttpWebRequest.CreateHttp(url);
var res = req.GetResponse() as HttpWebResponse;
var stream = res.GetResponseStream();
using (var sr = new StreamReader(stream))
{
var html = sr.ReadToEnd();
Console.WriteLine(html);
}
}
}
<Reference>
반응형
'C# 기초' 카테고리의 다른 글
[C# 교과서] 38. C# 확장 기능(13) - 함수와 함수형 프로그래밍 (0) | 2022.01.27 |
---|---|
[C# 교과서] 36. C# 확장 기능(11) - XML과 JSON (0) | 2022.01.26 |
[C# 교과서] 35. C# 확장 기능(10) - 스트림과 파일 입출력 (0) | 2022.01.26 |
[C# 교과서] 34. C# 확장 기능(9) - 인메모리 데이터베이스 프로그래밍 (0) | 2022.01.26 |
[C# 교과서] 33. C# 확장 기능(8) - 비동기 프로그래밍 (0) | 2022.01.26 |
Comments