-
-
Save NDiiong/31d529c73eba666c117607cfdb184f90 to your computer and use it in GitHub Desktop.
HttpClient Sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static HttpClient client = new HttpClient(); | |
// GET | |
var response = await client.GetAsync(@"http://localhost/admin"); | |
var cookies = response.Headers.FirstOrDefault(pair => String.Compare(pair.Key, @"Set-Cookie", StringComparison.OrdinalIgnoreCase) == 0).Value; | |
// get token from html | |
var html = await response.Content.ReadAsStringAsync(); | |
var regex = new Regex("(name=\\\"_token\\\" value=)\\\"(.*)\\\""); | |
var token = regex.Match(html).Groups[2].Value; | |
Debug.WriteLine($"token {token}"); | |
// ログイン POST | |
var request = new HttpRequestMessage(HttpMethod.Post, @"http://localhost/admin/login") | |
{ | |
Content = new FormUrlEncodedContent(new Dictionary<string, string> | |
{ | |
{"email", "admin@admin.com"}, | |
{"password", "password"}, | |
{"_token", token}, | |
}) | |
}; | |
request.Headers.Add(@"Cookie", cookies); | |
var response2 = await client.SendAsync(request); | |
//var bytes1 = await response2.Content.ReadAsByteArrayAsync(); | |
//File.WriteAllBytes(@"D:\UserData\naohba\Desktop\ログインできた?.html", bytes1); | |
// get token from html | |
html = await response2.Content.ReadAsStringAsync(); | |
token = regex.Match(html).Groups[2].Value; | |
Debug.WriteLine($"token {token}"); | |
// カテゴリ登録 | |
cookies = response2.Headers.FirstOrDefault(pair => String.Compare(pair.Key, @"Set-Cookie", StringComparison.OrdinalIgnoreCase) == 0).Value; | |
var request2 = new HttpRequestMessage(HttpMethod.Post, @"http://localhost/admin/categories") | |
{ | |
Content = new FormUrlEncodedContent(new Dictionary<string, string> | |
{ | |
{"order", "6"}, | |
{"name", "Category 6"}, | |
{"slug", "category-6"}, | |
{"_token", token}, | |
}) | |
}; | |
request2.Headers.Add(@"Cookie", cookies); | |
var response3 = await client.SendAsync(request2); | |
//var bytes2 = await response3.Content.ReadAsByteArrayAsync(); | |
//File.WriteAllBytes(@"D:\UserData\naohba\Desktop\カテゴリ登録.html", bytes2); | |
Debug.WriteLine("******"); | |
Debug.WriteLine(response3.StatusCode == HttpStatusCode.OK ? "★★★ OK ★★★" : $"★★★ NG ★★★ {response3.StatusCode}"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment