a developer's notes – a semi-technical web development BLOG

December 19, 2014

Web API 2 – Sample HttpClient and Sample WebClient call

Filed under: C# — Duy Nguyen @ 11:29 am
Tags: , , , ,

Here is a sample request using the old WebClient.

//GET
using (var client = new WebClient())
{
	try
	{
		client.BaseAddress = "http://localhost/endpoint";
		// HTTP GET
		client.UseDefaultCredentials = true;
		jsonResponse = client.DownloadString(endpoint);
	}
	catch (WebException ex)
	{
		// Http Error
		if (ex.Status == WebExceptionStatus.ProtocolError)
		{
			HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
			var statusCode = (int)wrsp.StatusCode;
			var msg = wrsp.StatusDescription;
			throw new HttpException(statusCode, msg);
		}
		else
		{
			throw new HttpException(500, ex.Message);
		}
	}
}

//Post
public string PostRequest(string endpoint, NameValueCollection requestParams)
{
	// Create string to hold JSON response
	string jsonResponse = string.Empty;

	using (var client = new WebClient())
	{
		try
		{
			client.UseDefaultCredentials = true;
			client.Headers.Add("Content-Type:application/x-www-form-urlencoded");
			client.Headers.Add("Accept:application/json");
			var uri = new Uri(endpoint);
			var response = client.UploadValues(uri, "POST", requestParams);
			jsonResponse = Encoding.ASCII.GetString(response);
		}
		catch (WebException ex)
		{
			// Http Error
			if (ex.Status == WebExceptionStatus.ProtocolError)
			{
				HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
				var statusCode = (int)wrsp.StatusCode;
				var msg = wrsp.StatusDescription;
				throw new HttpException(statusCode, msg);
			}
			else
			{
				throw new HttpException(500, ex.Message);
			}
		}
	}

	return jsonResponse;
}

// Post Json
public string PostRequestJson(string endpoint, string json)
{
	// Create string to hold JSON response
	string jsonResponse = string.Empty;

	using (var client = new WebClient())
	{
		try
		{
			client.UseDefaultCredentials = true;
			client.Headers.Add("Content-Type:application/json");
			client.Headers.Add("Accept:application/json");
			var uri = new Uri(endpoint);
			var response = client.UploadString(uri, "POST", json);
			jsonResponse = response;
		}
		catch (WebException ex)
		{
			// Http Error
			if (ex.Status == WebExceptionStatus.ProtocolError)
			{
				HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
				var statusCode = (int)wrsp.StatusCode;
				var msg = wrsp.StatusDescription;
				throw new HttpException(statusCode, msg);
			}
			else
			{
				throw new HttpException(500, ex.Message);
			}
		}
	}

	return jsonResponse;
}


Here is a sample request using the new HttpClient.


HttpClientHandler handler = new HttpClientHandler()
{
	PreAuthenticate = true,
	UseDefaultCredentials = true
};


string reasonPhrase = "";
using (var client = new HttpClient(handler))
{
	client.BaseAddress = new Uri("http://localhost/endpoint");
	client.DefaultRequestHeaders.Accept.Clear();
	client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
	
	// GET
	var response = client.GetAsync(endpoint).Result;
	// Post
	// var response = client.PostAsJsonAsync("http://localhost/endpoint", obj).Result;
	
	if (response.IsSuccessStatusCode)
	{
		var result = response.Content.ReadAsStringAsync().Result;
		return result;
	}
	else
	{
		reasonPhrase = response.ReasonPhrase;
		if (reasonPhrase.ToUpper() == "UNAUTHORIZED")
		{
			throw new KeyNotFoundException("Not authorized");
		}
		var apps = response.Content.ReadAsAsync<ResponseHeader>().Result;
		if (apps.ReturnCode.ToUpper() == "NOTFOUND" )
		{		
			throw new KeyNotFoundException(apps.Result);
		}
		else
		{
			throw new SystemException(apps.Result);
		}
	}
}

Blog at WordPress.com.