728x90
728x170
■ WebClient 클래스를 사용해 서버 인코딩 타입에 맞춰 문자열을 다운로드하는 방법을 보여준다.
▶ 예제 코드 (C#)
using System.Net;
using System.Text;
#region 문자열 다운로드하기 - DownloadString(webClient, url)
/// <summary>
/// 문자열 다운로드하기
/// </summary>
/// <param name="webClient">웹 클라이언트</param>
/// <param name="url">URL</param>
/// <returns>다운로드 문자열</returns>
public string DownloadString(WebClient webClient, string url)
{
const string charsetKey = "charset";
byte[] dataByteArray = webClient.DownloadData(url);
string contentType = webClient.ResponseHeaders["Content-Type"];
int charsetPosition = contentType.IndexOf(charsetKey);
Encoding currentEncoding = Encoding.Default;
if(charsetPosition != -1)
{
charsetPosition = contentType.IndexOf("=", charsetPosition + charsetKey.Length);
if(charsetPosition != -1)
{
string charset = contentType.Substring(charsetPosition + 1);
currentEncoding = Encoding.GetEncoding(charset);
}
}
return currentEncoding.GetString(dataByteArray);
}
#endregion
728x90
그리드형(광고전용)
'C# > Common' 카테고리의 다른 글
[C#/COMMON] FileSystem 클래스 : CopyDirectory 정적 메소드를 사용해 디렉토리 복사하기 (0) | 2022.05.25 |
---|---|
[C#/COMMON] Marshal 클래스 : Copy 정적 메소드를 사용해 문자열을 fixed char 필드에 복사하기 (0) | 2022.05.25 |
[C#/COMMON] DynamicMethod 클래스 : Invoke 메소드를 사용해 구조체 크기 구하기 (0) | 2022.05.25 |
[C#/COMMON] MemoryMappedFile 클래스 : CreateNew 정적 메소드를 사용해 시스템 메모리에서 메모리 매핑 파일 만들기 (0) | 2022.05.25 |
[C#/COMMON/.NET5] 콘솔 폰트 설정하기 (0) | 2022.05.24 |
[C#/COMMON] 이스케이프 유니코드 문자열 구하기 (0) | 2022.05.23 |
[C#/COMMON] Process 클래스 : 원격 데스크톱 실행하기 (0) | 2022.05.13 |
[C#/COMMON] Process 클래스 : 원격 데스크톱 계정 등록하기 (0) | 2022.05.13 |
[C#/COMMON] Regex 클래스 : Replace 정적 메소드를 사용해 한글 문자열 구하기 (0) | 2022.05.13 |
[C#/COMMON] IPAddress 클래스 : HostToNetworkOrder/NetworkToHostOrder 정적 메소드를 사용해 리틀 엔디안/빅 엔디안 값 변환하기 (0) | 2022.05.13 |