Answers for "httpclient c# tutorial"

C#
2

httpclient c# sample

// 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);
  }
}
Posted by: Guest on April-19-2021
3

example HttpClient c# Post

//Base code from: http://zetcode.com/csharp/httpclient/
public async string Example() 
{
  	//The data that needs to be sent. Any object works.
	var pocoObject = new 
	{
	  	Name = "John Doe",
		Occupation = "gardener"
	};

  	//Converting the object to a json string. NOTE: Make sure the object doesn't contain circular references.
	string json = JsonConvert.SerializeObject(pocoObject);
  	
  	//Needed to setup the body of the request
	StringContent data = new StringContent(json, Encoding.UTF8, "application/json");

  	//The url to post to.
	var url = "https://httpbin.org/post";
	var client = new HttpClient();

  	//Pass in the full URL and the json string content
	var response = await client.PostAsync(url, data);

  	//It would be better to make sure this request actually made it through
	string result = await response.Content.ReadAsStringAsync();
  	
  	//close out the client
  	client.Dispose();
  
	return result;
}
Posted by: Guest on June-12-2020
0

httpclient C#

//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;
}
Posted by: Guest on June-14-2021

C# Answers by Framework

Browse Popular Code Answers by Language