Skip to content

Instantly share code, notes, and snippets.

@heape
Last active November 1, 2019 10:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heape/3b3fb8828c13c9caa6700a3414ed3a0e to your computer and use it in GitHub Desktop.
Save heape/3b3fb8828c13c9caa6700a3414ed3a0e to your computer and use it in GitHub Desktop.
C# Http Request Wrapper (NOOB)
private async Task<HttpResponseMessage> Request(string url, HttpMethod method, Dictionary<string, string> headers, string body)
{
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
clientHandler.Proxy = null;
clientHandler.UseProxy = false;
clientHandler.UseCookies = false;
clientHandler.AllowAutoRedirect = false;
using (HttpClient client = new HttpClient(clientHandler))
{
try
{
foreach(var header in headers)
{
client.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
}
if (method == HttpMethod.Get)
{
HttpResponseMessage res = await client.GetAsync(url);
return res;
} else if(method == HttpMethod.Post || method == HttpMethod.Put)
{
var parameters = new Dictionary<string, string>();
{
};
var parts = body.Split('&');
foreach(var part in parts)
{
var param = part.Split('=');
if (param.Length >= 2)
{
parameters.Add(param[0], param[1]);
}
}
var content = new FormUrlEncodedContent(parameters);
var request = new HttpRequestMessage(method, url);
request.Content = content;
HttpResponseMessage res = await client.SendAsync(request);
return res;
}
} catch(Exception ex)
{
MessageBox.Show(ex.ToString()); // デバッグ用
return null; // nullを代入し、この関数を呼び出した関数ルーチン (button_Click) で適切な戻り値かどうか判断できるようにする
}
}
return null;
}
usage:
private async void button1_Click(object sender, EventArgs e)
{
await Task.Factory.StartNew(async () =>
{
var headers = new Dictionary<string, string>();
headers.Add("User-Agent", "Google BOT chan");
headers.Add("HELLO", "BOYZ");
var response = Request("http://localhost/test.php", HttpMethod.Get, headers, "").Result;
var responseBody = await response.Content.ReadAsStringAsync();
MessageBox.Show(responseBody);
});
}
@heape
Copy link
Author

heape commented Oct 31, 2019

localhost/test.php

<?php
var_dump(getallheaders());

@heape
Copy link
Author

heape commented Nov 1, 2019

[更新]
例外処理を追加、謝った実装を修正しました。

        private async Task<HttpResponseMessage> Request(string url, HttpMethod method, Dictionary<string, string> headers, string body)
        {
            HttpClientHandler clientHandler = new HttpClientHandler();

            clientHandler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            clientHandler.Proxy = null;
            clientHandler.UseProxy = false;
            clientHandler.UseCookies = false;
            clientHandler.AllowAutoRedirect = false;

            using (HttpClient client = new HttpClient(clientHandler))
            {
                try
                {
                    foreach(var header in headers)
                    {
                        client.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
                    }

                    if (method == HttpMethod.Get)
                    {
                        HttpResponseMessage res = await client.GetAsync(url);

                        return res;
                    } else if(method == HttpMethod.Post || method == HttpMethod.Put)
                    {
                        var parameters = new Dictionary<string, string>();
                        {
                        };

                        var parts = body.Split('&');
                        foreach(var part in parts)
                        {
                            var param = part.Split('=');
                            if (param.Length >= 2)
                            {
                                parameters.Add(param[0], param[1]);
                            }
                        }

                        var content = new FormUrlEncodedContent(parameters);

                        var request = new HttpRequestMessage(method, url);
                        request.Content = content;

                        HttpResponseMessage res = await client.SendAsync(request);

                        return res;
                    }

                } catch(Exception ex)
                {
                    MessageBox.Show(ex.ToString()); // デバッグ用
                    return null; // nullを代入し、この関数を呼び出した関数ルーチン (button_Click) で適切な戻り値かどうか判断できるようにする
                }
            }

            return null;
        }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment