Points to remember while accessing API using C# .

C# API access document
======================

Getting Started
---------------

There are two ways to access a web api request one is through WebClient and other one HttpWebRequest, we will take a look at the second option for accessing the api calls.

we made use of Fiddler tool to analyse the request sent from the system. Also we tried to find out the inner more details about the request.



Initialize HttpWebRequest
-------------------------

HttpWebRequest request = (HttpWebRequest) WebRequest.Create(apiURL);

how to set cookies for request?
-------------------------------

request.CookiesContainer = new CookiesContainer();

how to set the accept header for request?
-----------------------------------------

request.Accept = "*/*";

how to set KeepAlive as true?
-----------------------------

request.KeepAlive = true;

how to set Expect100Continue as false?
--------------------------------------

request.ServicePoint.Expect100Continue = false;

how to get the cookies from response of previous request?
---------------------------------------------------------

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

// HttpWebRequest anotherRequest = (HttpWebRequest) WebRequest.Create(apiURL2);
// ...

anotherRequest.SetCookies(response.GetCookies(request.Uri));

how to get the cookies and set the cookie collection as global
--------------------------------------------------------------

public class RequestUtility {

private CookiesContainer cookieJar = new CookiesContainer();
// ...

public void GetWebRequest(string apiURL) {

	HttpWebRequest request = (HttpWebRequest) WebRequest.Create(apiURL);
	request.CookiesContainer = cookieJar;
	HttpWebResponse response = (HttpWebResponse) request.GetResponse();
	
	// HttpWebRequest anotherRequest = (HttpWebRequest) WebRequest.Create(apiURL2);
	// ...

	anotherRequest.SetCookies(response.GetCookies(request.Uri));
}


Leave a Reply