LoginSignup
3
1

More than 5 years have passed since last update.

C# Httpクラス群使用でのGET, POST, HEAD

Posted at

※exceptionは処理を行わないで上に投げてるだけです。

本体

[TestHTTP.cs]
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;

namespace Test {
  public partial class TestHTTP {
    // "http://proxy.foo.com:8080"
    public String proxyurl = null;

    public TestHTTP () {;}

    private Dictionary<String, String> defaultRequestHeaders =
      new Dictionary<string, string> {
        {@"User-Agent", @"Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)"},
        {@"Accept-Language", @"ja-JP"}
      };
    protected CookieContainer cookieContainer = null;

    protected class SSHttpClientHandler : HttpClientHandler {
      public SSHttpClientHandler (String proxyurl) {
        if (proxyurl != null) {
          Proxy = new WebProxy (proxyurl);
          UseProxy = true;
        } else {
          Proxy = null;
          UseProxy = false;
        }
        // CookieContainer =
      }
    }

    protected class SendClientHandler : DelegatingHandler {
      public SendClientHandler () : base (new HttpClientHandler ()) {;}
      public SendClientHandler (HttpMessageHandler innerHandler) : base (innerHandler) {;}

      protected override async Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, CancellationToken cancellationToken) {
        HttpResponseMessage response = await base.SendAsync (request, cancellationToken).ConfigureAwait (false);
        return response;
      }
    }

    private TimeSpan waittime = Timeout.InfiniteTimeSpan;
    //TimeSpan.FromSeconds (800.0);

    protected HttpResponseHeaders GetHead (Uri uri, Dictionary<string, string> send, CancellationTokenSource cancellationTokenSource) {
      using (HttpClientHandler handler = new SSHttpClientHandler (proxyurl)) {
        using (HttpClient client = new HttpClient (new SendClientHandler (handler))) {
          foreach (KeyValuePair<String, String> h in defaultRequestHeaders)
            client.DefaultRequestHeaders.Add (h.Key, h.Value);
          client.Timeout = waittime;
          client.MaxResponseContentBufferSize = 256000;

          HttpRequestMessage request = new HttpRequestMessage ();
          request.Method = HttpMethod.Head;
          request.RequestUri = uri;

          if (send != null)
            request.Content = new FormUrlEncodedContent (send);

          try {
            Task<HttpResponseMessage> hTask = client.SendAsync (request, cancellationTokenSource.Token);
            hTask.Wait ();
            cookieContainer = handler.CookieContainer;
            return hTask.Result.Headers;
          } catch (HttpRequestException e) {
            Exception ex = e;
            while (ex != null) {
              ex = ex.InnerException;
            }
            throw;
          } catch (TaskCanceledException e) {
            throw;
          } catch (AggregateException e) {
            Exception ex = e;
            while (ex != null) {
              ex = ex.InnerException;
            }
            throw;
          }
        }
      }
    }

    protected async Task<String> WebAsync (Uri uri, HttpMethod method, Dictionary<string, string> send, CancellationTokenSource cancellationTokenSource) {
      using (HttpClientHandler handler = new SSHttpClientHandler (proxyurl)) {
        using (HttpClient client = new HttpClient (new SendClientHandler (handler))) {
          foreach (KeyValuePair<String, String> h in defaultRequestHeaders)
            client.DefaultRequestHeaders.Add (h.Key, h.Value);
          client.Timeout = waittime;
          client.MaxResponseContentBufferSize = 256000;

          HttpRequestMessage request = new HttpRequestMessage ();
          request.Method = method;
          request.RequestUri = uri;

          if (send != null)
            request.Content = new FormUrlEncodedContent (send);

          try {
            Task<HttpResponseMessage> hTask = client.SendAsync (request, cancellationTokenSource.Token);
            hTask.Wait ();
            HttpResponseMessage response = hTask.Result;
            cookieContainer = handler.CookieContainer;
            if (response.IsSuccessStatusCode)
              using (StreamReader reader = new StreamReader (await response.Content.ReadAsStreamAsync ()))
                return reader.ReadToEndAsync ().Result;
          } catch (HttpRequestException e) {
            Exception ex = e;
            while (ex != null) {
              ex = ex.InnerException;
            }
            throw;
          } catch (TaskCanceledException e) {
            throw;
          } catch (AggregateException e) {
            Exception ex = e;
            while (ex != null) {
              ex = ex.InnerException;
            }
            throw;
          }
        }
      }
      return null;
    }

    public HttpResponseHeaders GetWebHead (Uri uri, Dictionary<string, string> send, CancellationTokenSource cancellationTokenSource) {
      return GetHead (uri, send, cancellationTokenSource);
    }

    public async Task<String> GetWebAsync (Uri uri, Dictionary<string, string> send, CancellationTokenSource cancellationTokenSource) {
      return await WebAsync (uri, HttpMethod.Get, send, cancellationTokenSource);
    }

    public async Task<String> PostWebAsync (Uri uri, Dictionary<string, string> send, CancellationTokenSource cancellationTokenSource) {
      return await WebAsync (uri, HttpMethod.Post, send, cancellationTokenSource);
    }
  }
}

呼び出し側

private System.Windows.Forms.TextBox log;
private System.Windows.Forms.Button getweb;
private System.Windows.Forms.Button head;
[Test.cs]
    private void getweb_Click (Object sender, EventArgs e) {
      TestHTTP http = new TestHTTP ();
      // Uri uri = new Uri (@"http://www.google.co.jp/");
      Uri uri = new Uri (@"http://www.yahoo.co.jp/");
      String r = http.GetWebAsync (uri, null, new CancellationTokenSource ()).Result;
      LogOut (r);
    }

    private void head_Click (Object sender, EventArgs e) {
      TestHTTP http = new TestHTTP ();
      Uri uri = new Uri (@"http://www.yahoo.co.jp/");
      HttpResponseHeaders r = http.GetWebHead (uri, null, new CancellationTokenSource ());
      LogOut (r.ToString ());
    }
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1