httpclient C#

// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();

static async Task Main()
{
  // Call asynchronous network methods in a try/catch block to handle exceptions.
  try	
  {
     HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
     response.EnsureSuccessStatusCode();
     string responseBody = await response.Content.ReadAsStringAsync();
     // Above three lines can be replaced with new helper method below
     // string responseBody = await client.GetStringAsync(uri);

     Console.WriteLine(responseBody);
  }
  catch(HttpRequestException e)
  {
     Console.WriteLine("\nException Caught!");	
     Console.WriteLine("Message :{0} ",e.Message);
  }
}

0
6
Katboodle 145 points

                                    //example code
//var lst = await service.ConnectHttpClient<User, List<User>>("api/User/GetUserInfoByUserId", new User() { UserId = 1 });
//var lst = await service.ConnectRestClient<User, List<User>>("api/User/GetUserInfoByUserId", new User() { UserId = 1 });

public async Task<M> ConnectHttpClient<R, M>(string apiUrl, R reqModel)
{
    M model = default(M);

    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri(baseUrl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    HttpResponseMessage response = await client.PostAsJsonAsync(apiUrl, reqModel);
    if (response.IsSuccessStatusCode)
    {
        var res = response.Content.ReadAsStringAsync().Result;
        model = JsonConvert.DeserializeObject<M>(res);
    }
    return model;
}

public async Task<M> ConnectRestClient<R, M>(string apiUrl, R reqModel)
{
    M model = default(M);

    RestClient restClient = new RestClient(baseUrl);
    RestRequest restRequest = new RestRequest(apiUrl, Method.POST, DataFormat.Json);
    restRequest.AddJsonBody(reqModel);
    IRestResponse restResponse = await restClient.ExecuteAsync(restRequest);
    if (restResponse.IsSuccessful)
    {
        string response = restResponse.Content;
        model = JsonConvert.DeserializeObject<M>(response);
    }
    return model;
}

0
0
Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source