첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.

728x90
반응형
728x170

▶ HttpClient 클래스 : 프록시 사용하기 예제

string content = await GetStringAsync("http://192.168.72.10:8888", "http://www.daum.net");

 

728x90

 

▶ HttpClient 클래스 : 프록시 사용하기

using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

#region 문자열 구하기 (비동기) - GetStringAsync(proxyURL, url)

/// <summary>
/// 문자열 구하기 (비동기)
/// </summary>
/// <param name="proxyURL">프록시 URL</param>
/// <param name="url">URL</param>
/// <returns>문자열</returns>
public async Task<string> GetStringAsync(string proxyURL, string url)
{
    string content = string.Empty;

    try
    {
        ServicePointManager.Expect100Continue = false;

        ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

        WebProxy proxy = new WebProxy { Address = new Uri(proxyURL) };

        HttpClientHandler clientHandler = new HttpClientHandler()
        {
            AllowAutoRedirect      = true,
            AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip,
            Proxy                  = proxy,
        };

        using(HttpClient client = new HttpClient(clientHandler))
        {
            client.DefaultRequestHeaders.Accept.Clear();

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));

            client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");

            HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url);

            HttpResponseMessage httpResponseMessage = await client.SendAsync(httpRequestMessage);

            if(httpResponseMessage.StatusCode == HttpStatusCode.OK)
            {
                content = await httpResponseMessage.Content.ReadAsStringAsync();
            }
        }
    }
    catch(HttpRequestException)
    {
        throw;
    }

    return content;
}

#endregion
728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요