Send Get and Post Request to Http Server - CSharp System.Net

CSharp examples for System.Net:Http

Description

Send Get and Post Request to Http Server

Demo Code


using System;/*ww  w  .  j a va2s .  com*/
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;

namespace HttpHelper
{
    public static class BaseService
    {
        public static CookieContainer CookiesContainer;
 
        public async static Task<string> SendGetRequest(string url)
        {
            try
            {
                HttpClient client = new HttpClient();
                HttpResponseMessage response = await client.GetAsync(new Uri(url));
                response.EnsureSuccessStatusCode();
                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                return null;
                throw(ex);
            }
        }

        public async static Task<string> SendPostRequest(string url,string body)
        {
            try
            {
                HttpClient client = new HttpClient();
                HttpResponseMessage response = await client.PostAsync(new Uri(url), new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("", body) }));
                response.EnsureSuccessStatusCode();
                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                return null;
                throw(ex);
            }
        }
    }
}

Related Tutorials