WebClient

 

WebClient 는 HTTP를 이용해서 외부 리소스나 문자열을 다운로드/업로드 할 때 사용하는 클래스입니다.

HttpWebRequest / HttpWebResponse에 비해 단순한 기능만 제공하므로, 쉽습니다.

 

Async : asynchronous communication, 비동기통신

 

WebClient에서 제공되는 메서드

DownloadStringAsync / Get / 문자열 타입 / 문자열을 다운로드

UploadStringAsync / Post / 문자열 타입 / 문자열을 업로드

OpenReadAsync / Get / 리소스 타입 / 리소스를 다운로드

OpenWriteAsync / Post / 리소스 타입 / 리소스를 업로드

CancelAsync / 업로드나 다운로드를 취소합니다.

 

* 문자열 타입은 일반 Text나 HTML, XML등을 의미하고,

   리소스 타입은 이미지나 동영상을 등을 의미합니다.

 

WebCliend에서 제공되는 이벤트

DownloadStringCompleted / 문자열 다운로드가 완료 혹은 실패한 경우
DownloadProgressChanged / 문자열 다운로드 양이 변화된 경우
UploadStringCompleted / 문자열 업로드가 완료 혹은 실패한 경우
UploadProgressChanged / 문자열 업로드 양이 변화된 경우

OpenReadCompleted / 리소스를 다운받기 위한 스트림이 열린 경우

OpenWriteCompleted / 리소스를 업로드 하기 위한 스트림이 열린 경우

WriteStreamClosed / 리소스를 업로드 하기 위한 스트림이 닫힌 경우

 

WebClient 이용해서 문자열 다운로드 하기

MainPage.xaml

<Grid x:Name="LayoutRoot" >
 <Grid.RowDefinitions>
  <RowDefinition Height="Auto"/>
  <RowDefinition Height="Auto"/>
  <RowDefinition Height="Auto"/>
 </Grid.RowDefinitions>
 <Grid.ColumnDefinitions>
  <ColumnDefinition Width="Auto"/>
 </Grid.ColumnDefinitions>
 <TextBlock Text="다운로드 결과"/>
 <Border Grid.Row="1" BorderBrush="Black" BorderThickness="1">
  <TextBlock x:Name="tbResult" Width="400" Height="300" />
 </Border>
 <Button x:Name="btRequest" Width="Auto" Height="Auto" Content="다운로드" Grid.Row="2" />
</Grid>

 

MainPage.xaml.cs

public partial class MainPage : UserControl 
{
 public MainPage()
 {
  InitializeComponent();
  btRequest.Click += new RoutedEventHandler(btRequest_Click);
 }
 void btRequest_Click(object sender, RoutedEventArgs e)
 {
  WebClient client = new WebClient();
  client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
  client.DownloadStringAsync(
   new Uri("http://antasis9.woweb.net/silverlight/hello.txt", UriKind.Absolute)
  );
 }
 void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
 {
  tbResult.Text = e.Result.ToString();
 }
} 

WebClient 이용해서 리소스 다운로드 하기

MainPage.xaml

<Grid x:Name="LayoutRoot">
 <Grid.RowDefinitions>
  <RowDefinition Height="100"/>
  <RowDefinition Height="30"/>
 </Grid.RowDefinitions>
 <StackPanel Grid.Row="0" 
    VerticalAlignment="Center" HorizontalAlignment="Center" 
    Orientation="Horizontal">
  <TextBlock Text="다운로드양: " FontSize="20" FontWeight="Bold"/>
  <TextBlock x:Name="tbDownloadPercent" Text="0" FontSize="20" FontWeight="Bold"/>
  <TextBlock Text="%" FontSize="20" FontWeight="Bold"/>
 </StackPanel>
 <Button x:Name="btRequest"
    Width="100" Height="30" Content="다운로드" Grid.Row="1"/>
</Grid>

MainPage.xaml.cs

public partial class MainPage : UserControl
{
 public MainPage()
 {
  InitializeComponent();
  btRequest.Click += new RoutedEventHandler(btRequest_Click);
 }
 void btRequest_Click(object sender, RoutedEventArgs e)
 {
  WebClient client = new WebClient();
  // 다운로드 양이 변경되면 호출되는 이벤트의 핸들러
  client.DownloadProgressChanged +=
   new DownloadProgressChangedEventHandler(DownloadProgressChanged);
  // 다운로드 준비가 되면 호출되는 이벤트의 핸들러
  client.OpenReadCompleted += 
   new OpenReadCompletedEventHandler(OpenReadCompleted);
  // 다운로드 시작
  client.OpenReadAsync
   (new Uri("http://antasis9.woweb.net/silverlight/SilverlightApplication3.xap", 
    UriKind.Absolute));
 }
 void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
 {
  // 다운로드 양이 변경되면 화면에 출력
  tbDownloadPercent.Text = e.ProgressPercentage.ToString();
 }
 void OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
 {
  byte[] buffer = new byte[1024];
  // 격리된 저장 공간에 파일 생성
  IsolatedStorageFile store = 
   IsolatedStorageFile.GetUserStoreForApplication();
  StreamWriter sw = 
   new StreamWriter(store.OpenFile("test.zip", FileMode.Create));
  // 네트워크에서 1024 바이트씩 읽어옴
  while (e.Result.Read(buffer, 0, 1024) != 0)
  {
   // 파일에 기록
   sw.Write(buffer);
  }  
  sw.Close();
 }
}

 

* Silverlight는 다른 하위 도메인, 다른 프로토콜, 다른 호스트, 다른 포트에 대해 보안 에러를 발생시킵니다.

오직 같은 도메인, 같은 프로토콜, 같은 포트에 대해서만 접근이 가능합니다.

 

이것을 해결하기 위해서는 외부 서버에서 미리 허가를 받아야 합니다.

접속하고자 하는 서버의 관리자는 실버라이트에서 쓰이는 특정 보안 정책 파일을 해당 도메인에 넣어 줍니다.

그러면 실버라이트 애플리케이션은 미리 약속된 도메인임을 알아채고 보안 문제에 걸리지 않고 서비스를 계속해서 수핼 할  수 있게 됩니다.

 

1) 실버라이트 도메인 정책 파일 (clientaccesspolicy.xml) 

<?xml version="1.0" encoding="utf-8" ?>
<access-policy>
 <cross-domain-access>
  <policy>
   <allow-from http-request-headers="*">
    <domain uri="*" />
   <allow-from>
   <grant-to>
    <resource path="/" include-subpaths="true" />
   </grant-to>
  </policy>
 </cross-domain-access>
</access-policy>

 

2) 플래시 도메인 정책 파일

<?xml version="1.0" ?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml.dtds/cross-domain-policy.dtd">
<cross-domain-policy>
 <allow-access-from domain="*" headers="*" secure="true" />
</cross-domain-policy>