@@ -4,42 +4,25 @@ namespace HttpClientToCurl.Sample.InString;
44
55public 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+ private const string AccessToken = "YourAccessToken" ;
11+
712 public static async Task MakeApiCall ( )
813 {
9- string apiUrl = "https://jsonplaceholder.typicode.com/posts" ;
10-
11- // Create an instance of HttpClient
12- HttpClient client = new ( ) ;
13-
1414 try
1515 {
1616 // Create a sample JSON payload
17- string jsonPayload =
18- "{\" title\" :\" New Post\" ,\" body\" :\" This is the body of the new post\" ,\" userId\" :1}" ;
19-
20- // Create HttpRequestMessage with the POST verb
21- HttpRequestMessage request = new ( HttpMethod . Post , apiUrl ) ;
22-
23- // Set up the request headers
24- request . Headers . Add ( "Authorization" , "Bearer YourAccessToken" ) ; // Add any necessary headers
25-
26- // Set the request content with the JSON payload
27- request . Content = new StringContent ( jsonPayload , Encoding . UTF8 , "application/json" ) ;
17+ var jsonPayload = "{\" title\" :\" New Post\" ,\" body\" :\" This is the body of the new post\" ,\" userId\" :1}" ;
2818
2919 // Generate a curl command as a string for debugging or testing.
30- // This string can be directly imported into Postman for checking and comparing against all the requirements.
31- string curlCommandString = client . GenerateCurlInString ( request ) ;
32-
33- Console . WriteLine ( curlCommandString ) ;
34-
35- // Send the request
36- HttpResponseMessage response = await client . SendAsync ( request ) ;
20+ var response = await SendHttpRequest ( HttpMethod . Post , ApiUrl , jsonPayload ) ;
3721
3822 // Check if the request was successful (status code 200-299)
3923 if ( response . IsSuccessStatusCode )
4024 {
41- // Read and print the response content as a string
42- string responseBody = await response . Content . ReadAsStringAsync ( ) ;
25+ var responseBody = await response . Content . ReadAsStringAsync ( ) ;
4326 Console . WriteLine ( "Response from the API:\n " + responseBody ) ;
4427 }
4528 else
@@ -52,4 +35,18 @@ public static async Task MakeApiCall()
5235 Console . WriteLine ( $ "Exception: { ex . Message } ") ;
5336 }
5437 }
38+
39+ private static async Task < HttpResponseMessage > SendHttpRequest ( HttpMethod method , string url , string payload = null )
40+ {
41+ var request = new HttpRequestMessage ( method , url ) ;
42+
43+ request . Headers . Add ( "Authorization" , $ "Bearer { AccessToken } ") ;
44+ request . Content = new StringContent ( payload , Encoding . UTF8 , "application/json" ) ;
45+
46+ Console . WriteLine ( GenerateCurl ( request ) ) ;
47+
48+ return await Client . SendAsync ( request ) ;
49+ }
50+
51+ private static string GenerateCurl ( HttpRequestMessage request ) => Client . GenerateCurlInString ( request ) ;
5552}
0 commit comments