Skip to content

Commit c087337

Browse files
Refactor examples with adding HttpRequestMessage scenarios
1 parent 480c32b commit c087337

File tree

7 files changed

+164
-55
lines changed

7 files changed

+164
-55
lines changed

examples/HttpClientToCurl.Sample.InConsole/ApiCaller.cs

Lines changed: 53 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,36 +4,36 @@ namespace HttpClientToCurl.Sample.InConsole;
44

55
public static class ApiCaller
66
{
7+
// Create an instance of HttpClient
8+
private static readonly HttpClient Client = new();
9+
private const string ApiUrl = "https://jsonplaceholder.typicode.com/posts";
10+
711
public static async Task MakeApiCall()
812
{
9-
string apiUrl = "https://jsonplaceholder.typicode.com/posts";
10-
11-
// Create an instance of HttpClient
12-
HttpClient client = new();
13-
1413
try
1514
{
1615
// Create a sample JSON payload
17-
string jsonPayload =
18-
"{\"title\":\"New Post\",\"body\":\"This is the body of the new post\",\"userId\":1}";
16+
string requestBody = /*lang=json,strict*/ @"{""name"":""sara"",""requestId"":10001001,""amount"":20000}";
1917

2018
// Create HttpRequestMessage with the POST verb
21-
HttpRequestMessage request = new(HttpMethod.Post, apiUrl);
19+
HttpRequestMessage httpRequestMessage = new(HttpMethod.Post, ApiUrl);
2220

2321
// Set up the request headers
24-
request.Headers.Add("Authorization", "Bearer YourAccessToken"); // Add any necessary headers
22+
httpRequestMessage.Headers.Add("Authorization", "Bearer YourAccessToken"); // Add any necessary headers
2523

2624
// Set the request content with the JSON payload
27-
request.Content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
25+
httpRequestMessage.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
2826

29-
// Log the curl command for debugging or testing.
30-
// This generates a curl command that can be imported into Postman.
31-
// Use it to check and compare against all the requirements.
27+
/* Generate a curl command and print it in the console for debugging or testing.
28+
This command can be imported into Postman for checking and comparing against all the requirements. */
3229

33-
client.GenerateCurlInConsole(request);
30+
// *** First Scenario ***
31+
GenerateCurlByHttpClient(httpRequestMessage);
32+
// *** Second Scenario ***
33+
GenerateCurlByHttpRequestMessage(httpRequestMessage);
3434

3535
// Send the request
36-
HttpResponseMessage response = await client.SendAsync(request);
36+
HttpResponseMessage response = await Client.SendAsync(httpRequestMessage);
3737

3838
// Check if the request was successful (status code 200-299)
3939
if (response.IsSuccessStatusCode)
@@ -52,4 +52,42 @@ public static async Task MakeApiCall()
5252
Console.WriteLine($"Exception: {ex.Message}");
5353
}
5454
}
55+
56+
#region << Private Methods >>
57+
58+
private static void GenerateCurlByHttpClient(HttpRequestMessage httpRequestMessage)
59+
{
60+
Console.WriteLine("* Generate Curl By HttpClient:");
61+
62+
// config is optional
63+
Client.GenerateCurlInConsole(httpRequestMessage, config =>
64+
{
65+
// Customize console configuration if needed
66+
config.TurnOn = true; // Enable generating curl command to the console
67+
config.NeedAddDefaultHeaders = true; // Specify if default headers should be included
68+
config.EnableCodeBeautification = true;
69+
config.EnableCompression = false;
70+
});
71+
72+
Console.WriteLine();
73+
}
74+
75+
private static void GenerateCurlByHttpRequestMessage(HttpRequestMessage httpRequestMessage)
76+
{
77+
Console.WriteLine("* Generate Curl By HttpRequestMessage:");
78+
79+
// config is optional
80+
httpRequestMessage.GenerateCurlInConsole(new Uri(ApiUrl), config =>
81+
{
82+
// Customize console configuration if needed
83+
config.TurnOn = true; // Enable generating curl command to the console
84+
config.NeedAddDefaultHeaders = true; // Specify if default headers should be included
85+
config.EnableCodeBeautification = true;
86+
config.EnableCompression = false;
87+
});
88+
89+
Console.WriteLine();
90+
}
91+
92+
#endregion << Private Methods >>
5593
}

examples/HttpClientToCurl.Sample.InConsole/HttpClientToCurl.Sample.InConsole.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
5-
<TargetFramework>net8.0</TargetFramework>
5+
<TargetFramework>net9.0</TargetFramework>
66
<ImplicitUsings>enable</ImplicitUsings>
77
<Nullable>enable</Nullable>
88
</PropertyGroup>

examples/HttpClientToCurl.Sample.InFile/ApiCaller.cs

Lines changed: 56 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4,42 +4,36 @@ namespace HttpClientToCurl.Sample.InFile;
44

55
public static class ApiCaller
66
{
7+
// Create an instance of HttpClient
8+
private static readonly HttpClient Client = new();
9+
private const string ApiUrl = "https://jsonplaceholder.typicode.com/posts";
10+
711
public static async Task MakeApiCall()
812
{
9-
string apiUrl = "https://jsonplaceholder.typicode.com/posts";
10-
11-
// Create an instance of HttpClient
12-
HttpClient client = new();
13-
1413
try
1514
{
1615
// Create a sample JSON payload
17-
string jsonPayload =
18-
"{\"title\":\"New Post\",\"body\":\"This is the body of the new post\",\"userId\":1}";
16+
string requestBody = /*lang=json,strict*/ @"{""name"":""sara"",""requestId"":10001001,""amount"":20000}";
1917

2018
// Create HttpRequestMessage with the POST verb
21-
HttpRequestMessage request = new(HttpMethod.Post, apiUrl);
19+
HttpRequestMessage httpRequestMessage = new(HttpMethod.Post, ApiUrl);
2220

2321
// Set up the request headers
24-
request.Headers.Add("Authorization", "Bearer YourAccessToken"); // Add any necessary headers
22+
httpRequestMessage.Headers.Add("Authorization", "Bearer YourAccessToken"); // Add any necessary headers
2523

2624
// Set the request content with the JSON payload
27-
request.Content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
25+
httpRequestMessage.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
2826

29-
// Generate a curl command and write it to a file for debugging or testing.
30-
// This command can be imported into Postman for checking and comparing against all the requirements.
31-
// config is optional
32-
client.GenerateCurlInFile(request, config =>
33-
{
34-
// Customize file configuration if needed
35-
config.TurnOn = true; // Enable generating curl command to file
36-
config.Filename = "curl_commands.txt"; // Specify the file name
37-
config.Path = "C:\\Path\\To\\Directory"; // Specify the directory path
38-
config.NeedAddDefaultHeaders = true; // Specify if default headers should be included
39-
});
27+
/* Generate a curl command and write it to a file for debugging or testing.
28+
This command can be imported into Postman for checking and comparing against all the requirements. */
29+
30+
// *** First Scenario ***
31+
GenerateCurlByHttpClient(httpRequestMessage);
32+
// *** Second Scenario ***
33+
GenerateCurlByHttpRequestMessage(httpRequestMessage);
4034

4135
// Send the request
42-
HttpResponseMessage response = await client.SendAsync(request);
36+
HttpResponseMessage response = await Client.SendAsync(httpRequestMessage);
4337

4438
// Check if the request was successful (status code 200-299)
4539
if (response.IsSuccessStatusCode)
@@ -58,4 +52,44 @@ public static async Task MakeApiCall()
5852
Console.WriteLine($"Exception: {ex.Message}");
5953
}
6054
}
55+
56+
#region << Private Methods >>
57+
58+
private static void GenerateCurlByHttpClient(HttpRequestMessage httpRequestMessage)
59+
{
60+
Console.WriteLine("* Generate Curl By HttpClient:");
61+
62+
// config is optional
63+
Client.GenerateCurlInFile(httpRequestMessage, config =>
64+
{
65+
// Customize file configuration if needed
66+
config.TurnOn = true; // Enable generating curl command to file
67+
config.NeedAddDefaultHeaders = true; // Specify if default headers should be included
68+
config.Filename = "curl_commands"; // Specify the file name
69+
config.Path = @"C:\Path\To\Directory"; // Specify the directory path !!
70+
});
71+
72+
Console.WriteLine("Done.");
73+
Console.WriteLine();
74+
}
75+
76+
private static void GenerateCurlByHttpRequestMessage(HttpRequestMessage httpRequestMessage)
77+
{
78+
Console.WriteLine("* Generate Curl By HttpRequestMessage:");
79+
80+
// config is optional
81+
httpRequestMessage.GenerateCurlInFile(new Uri(ApiUrl), config =>
82+
{
83+
// Customize file configuration if needed
84+
config.TurnOn = true; // Enable generating curl command to file
85+
config.NeedAddDefaultHeaders = true; // Specify if default headers should be included
86+
config.Filename = "curl_commands"; // Specify the file name
87+
config.Path = @"C:\Path\To\Directory"; // Specify the directory path !!
88+
});
89+
90+
Console.WriteLine("Done.");
91+
Console.WriteLine();
92+
}
93+
94+
#endregion << Private Methods >>
6195
}

examples/HttpClientToCurl.Sample.InFile/HttpClientToCurl.Sample.InFile.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
5-
<TargetFramework>net8.0</TargetFramework>
5+
<TargetFramework>net9.0</TargetFramework>
66
<ImplicitUsings>enable</ImplicitUsings>
77
<Nullable>enable</Nullable>
88
</PropertyGroup>

examples/HttpClientToCurl.Sample.InString/ApiCaller.cs

Lines changed: 49 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,39 @@ public static class ApiCaller
77
// Create an instance of HttpClient
88
private static readonly HttpClient Client = new();
99
private const string ApiUrl = "https://jsonplaceholder.typicode.com/posts";
10-
private const string AccessToken = "YourAccessToken";
1110

1211
public static async Task MakeApiCall()
1312
{
1413
try
1514
{
1615
// Create a sample JSON payload
17-
var jsonPayload = "{\"title\":\"New Post\",\"body\":\"This is the body of the new post\",\"userId\":1}";
16+
string requestBody = /*lang=json,strict*/ @"{""name"":""sara"",""requestId"":10001001,""amount"":20000}";
1817

19-
// Generate a curl command as a string for debugging or testing.
20-
var response = await SendHttpRequest(HttpMethod.Post, ApiUrl, jsonPayload);
18+
// Create HttpRequestMessage with the POST verb
19+
HttpRequestMessage httpRequestMessage = new(HttpMethod.Post, ApiUrl);
20+
21+
// Set up the request headers
22+
httpRequestMessage.Headers.Add("Authorization", "Bearer YourAccessToken"); // Add any necessary headers
23+
24+
// Set the request content with the JSON payload
25+
httpRequestMessage.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
26+
27+
/* Generate a curl command and set it to a string variable for debugging or testing.
28+
This command can be imported into Postman for checking and comparing against all the requirements. */
29+
30+
// *** First Scenario ***
31+
GenerateCurlByHttpClient(httpRequestMessage);
32+
// *** Second Scenario ***
33+
GenerateCurlByHttpRequestMessage(httpRequestMessage);
34+
35+
// Send the request
36+
HttpResponseMessage response = await Client.SendAsync(httpRequestMessage);
2137

2238
// Check if the request was successful (status code 200-299)
2339
if (response.IsSuccessStatusCode)
2440
{
25-
var responseBody = await response.Content.ReadAsStringAsync();
41+
// Read and print the response content as a string
42+
string responseBody = await response.Content.ReadAsStringAsync();
2643
Console.WriteLine("Response from the API:\n" + responseBody);
2744
}
2845
else
@@ -36,17 +53,37 @@ public static async Task MakeApiCall()
3653
}
3754
}
3855

39-
private static async Task<HttpResponseMessage> SendHttpRequest(HttpMethod method, string url, string payload = null)
56+
#region << Private Methods >>
57+
58+
private static void GenerateCurlByHttpClient(HttpRequestMessage httpRequestMessage)
4059
{
41-
var request = new HttpRequestMessage(method, url);
60+
// config is optional
61+
string curlResult = Client.GenerateCurlInString(httpRequestMessage, config =>
62+
{
63+
// Customize string variable configuration if needed
64+
config.TurnOn = true; // Enable generating curl command to string variable
65+
config.NeedAddDefaultHeaders = true; // Specify if default headers should be included
66+
});
4267

43-
request.Headers.Add("Authorization", $"Bearer {AccessToken}");
44-
request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
68+
Console.WriteLine("* Generate Curl By HttpClient:");
69+
Console.WriteLine(curlResult);
70+
Console.WriteLine();
71+
}
4572

46-
Console.WriteLine(GenerateCurl(request));
73+
private static void GenerateCurlByHttpRequestMessage(HttpRequestMessage httpRequestMessage)
74+
{
75+
// config is optional
76+
string curlResult = httpRequestMessage.GenerateCurlInString(new Uri(ApiUrl), config =>
77+
{
78+
// Customize string variable configuration if needed
79+
config.TurnOn = true; // Enable generating curl command to string variable
80+
config.NeedAddDefaultHeaders = true; // Specify if default headers should be included
81+
});
4782

48-
return await Client.SendAsync(request);
83+
Console.WriteLine("* Generate Curl By HttpRequestMessage:");
84+
Console.WriteLine(curlResult);
85+
Console.WriteLine();
4986
}
5087

51-
private static string GenerateCurl(HttpRequestMessage request) => Client.GenerateCurlInString(request);
88+
#endregion << Private Methods >>
5289
}

examples/HttpClientToCurl.Sample.InString/HttpClientToCurl.Sample.InString.csproj

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
5-
<TargetFramework>net8.0</TargetFramework>
5+
<TargetFramework>net9.0</TargetFramework>
66
<ImplicitUsings>enable</ImplicitUsings>
77
<Nullable>enable</Nullable>
88
</PropertyGroup>
99

1010
<ItemGroup>
11-
<ProjectReference Include="..\..\src\HttpClientToCurl\HttpClientToCurl.csproj" />
11+
<PackageReference Include="HttpClientToCurl" Version="2.0.7" />
1212
</ItemGroup>
1313

1414
</Project>

src/HttpClientToCurl/HttpClientToCurl.csproj

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22

33
<PropertyGroup>
44
<Authors>Amin Golmahalleh</Authors>
5-
<Version>2.0.6</Version>
6-
<PackageReleaseNotes>2.0.6</PackageReleaseNotes>
5+
<Version>2.0.7</Version>
6+
<PackageReleaseNotes>2.0.7</PackageReleaseNotes>
77
<TargetFramework>netstandard2.1</TargetFramework>
88
<ImplicitUsings>enable</ImplicitUsings>
99
<Nullable>disable</Nullable>

0 commit comments

Comments
 (0)