C# Docs

If this documentation is inaccurate or incomplete, please let us know your questions or suggested improvements.

Currently we do not plan to implement a native API for C#. However you can take full advantage of PhantomJsCloud by making HTTP Post Requests to our HTTP Endpoint. Below are some examples outlining how to invoke the HTTP Endpoint from C#

General Info

Avoiding 502 (Bad Gateway) Errors IMPORTANT

C# sets the ExpectContinue header to true by default. You must set it to false when you make requests or you will get 502 Bad Gateway errors for medium to large requests.

Post request body: (var pageRequestJson)

You should look at the HTTP Endpoint docs, section about userRequest and pageRequest for a listing of all the parameters you can pass via the pageRequestJson variable shown in these examples.

Basic Examples

Basic usage, using HttpClient (async)

using (var client = new System.Net.Http.HttpClient())
{
	client.DefaultRequestHeaders.ExpectContinue = false; //REQUIRED! or you will get 502 Bad Gateway errors
    //you should look at the HTTP Endpoint docs, section about "userRequest" and "pageRequest" 
    //for a listing of all the parameters you can pass via the "pageRequestJson" variable.
	var pageRequestJson = new System.Net.Http.StringContent(@"{'url':'http://example.com','renderType':'plainText','outputAsJson':false }");
	var response = await client.PostAsync("https://PhantomJScloud.com/api/browser/v2/a-demo-key-with-low-quota-per-ip-address/", pageRequestJson);
	var responseString = await response.Content.ReadAsStringAsync();
	Console.WriteLine("*** HTTP Request Finish ***");
	Console.WriteLine(responseString);
}
Basic usage, using WebRequest
try
{
	Console.WriteLine(String.Format("*** Begin Request ***"));
	var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://api.PhantomJScloud.com/api/browser/v2/a-demo-key-with-low-quota-per-ip-address/");
	request.ContentType = "application/json";
	request.Method = "POST";
	request.Timeout = 45000; //45 seconds
	request.KeepAlive = false;
	request.MediaType = "application/json";
	request.ServicePoint.Expect100Continue = false; //REQUIRED! or you will get 502 Bad Gateway errors
	using (var streamWriter = new System.IO.StreamWriter(request.GetRequestStream()))
	{
		//you should look at the HTTP Endpoint docs, section about "userRequest" and "pageRequest" 
		//for a listing of all the parameters you can pass via the "pageRequestJson" variable.
		string pageRequestJson = @"{'url':'http://example.com','renderType':'plainText','outputAsJson':false }";
		streamWriter.Write(pageRequestJson);
		streamWriter.Flush();
		streamWriter.Close();
	}
	var response = (System.Net.HttpWebResponse)request.GetResponse();
	Console.WriteLine(String.Format("HttpWebResponse.StatusDescription: {0}", response.StatusDescription));
	using (var streamReader = new System.IO.StreamReader(response.GetResponseStream()))
	{
		string server_reply = streamReader.ReadToEnd();
		Console.WriteLine(String.Format("Server Response content: {0}", server_reply));
	}
	response.Close();
}
catch (Exception Ex)
{
	Console.WriteLine("*** HTTP Request Error ***");
	Console.WriteLine(Ex.Message);
}

To be usable by all kinds of developers, the following examples use a non-async version of the HttpClient example code:

Minimal Example: Capture a Page as PlainText
This C# example captures the text from a page and prints to the command-line.

request.json
(in pageRequest format)
{
	"url":"http://example.com",
	"renderType":"plainText"
}

csharp code
using (var client = new System.Net.Http.HttpClient())
{
	client.DefaultRequestHeaders.ExpectContinue = false; //REQUIRED! or you will get 502 Bad Gateway errors
	var pageRequestJson = new System.Net.Http.StringContent(System.IO.File.ReadAllText("request.json"));
	var response = client.PostAsync("https://PhantomJScloud.com/api/browser/v2/a-demo-key-with-low-quota-per-ip-address/", pageRequestJson).Result;
	var responseString = response.Content.ReadAsStringAsync().Result;
	Console.WriteLine(responseString);                                         
	Console.WriteLine("*** Headers, pay attention to those starting with 'pjsc-' ***");
	Console.WriteLine(response.Headers);
}

Minimal Example: Verbose output JSON
This C# example Captures the text from the page and PhantomJsCloud metadata about the request and response, then saves to a .json file.

request.json
(in pageRequest format)
{
	"url":"http://example.com",
	"renderType":"plainText",
	"outputAsJson":true
}

csharp code
using (var client = new System.Net.Http.HttpClient())
{
	client.DefaultRequestHeaders.ExpectContinue = false; //REQUIRED! or you will get 502 Bad Gateway errors
	var pageRequestJson = new System.Net.Http.StringContent(System.IO.File.ReadAllText("request.json"));
	var response = client.PostAsync("https://PhantomJScloud.com/api/browser/v2/a-demo-key-with-low-quota-per-ip-address/", pageRequestJson).Result;
	var responseString = response.Content.ReadAsStringAsync().Result;
	System.IO.File.WriteAllText("response.json", responseString);                                         
	Console.WriteLine("*** Headers, pay attention to those starting with 'pjsc-' ***");
	Console.WriteLine(response.Headers);
}

Minimal Example: Capture as JPEG
This C# example will generate a screenshot of a webpage (including rendering AJAX), then saves to a .jpg file.

request.json
(in pageRequest format)
{
	"url":"http://www.highcharts.com/stock/demo/intraday-area",
	"renderType":"jpeg"
}

csharp code
using (var client = new System.Net.Http.HttpClient())
{
	client.DefaultRequestHeaders.ExpectContinue = false; //REQUIRED! or you will get 502 Bad Gateway errors
	var pageRequestJson = new System.Net.Http.StringContent(System.IO.File.ReadAllText("request.json"));
	var response = client.PostAsync("https://PhantomJScloud.com/api/browser/v2/a-demo-key-with-low-quota-per-ip-address/", pageRequestJson).Result;
	var responseStream = response.Content.ReadAsStreamAsync().Result;
	using (var fileStream = new System.IO.FileStream("content.jpg", System.IO.FileMode.Create))
	{
		responseStream.CopyTo(fileStream);
	}                                         
	Console.WriteLine("*** Headers, pay attention to those starting with 'pjsc-' ***");
	Console.WriteLine(response.Headers);
}

Minimal Example: Capture as PDF
This C# example will generate a PDF of Amazon.com's main page (the live, current contents), then saves to a .pdf file.

request.json
(in pageRequest format)
{
	"url":"https://amazon.com",
	"renderType":"pdf"
}

csharp code
using (var client = new System.Net.Http.HttpClient())
{
	client.DefaultRequestHeaders.ExpectContinue = false; //REQUIRED! or you will get 502 Bad Gateway errors
	var pageRequestJson = new System.Net.Http.StringContent(System.IO.File.ReadAllText("request.json"));
	var response = client.PostAsync("https://PhantomJScloud.com/api/browser/v2/a-demo-key-with-low-quota-per-ip-address/", pageRequestJson).Result;
	var responseStream = response.Content.ReadAsStreamAsync().Result;
	using (var fileStream = new System.IO.FileStream("content.pdf", System.IO.FileMode.Create))
	{
		responseStream.CopyTo(fileStream);
	}
	Console.WriteLine("*** Headers, pay attention to those starting with 'pjsc-' ***");
	Console.WriteLine(response.Headers);
}

Minimal Example: All parameters
This C# example shows using all PhantomJsCloud parameters in a request, capturing the page as a .jpg image and then saves the image to a file. Most the parameters used are the defaults, but you can see a list of the most up-to-date default values here.

request.json
(in userRequest format)
{
	"pages":[
		{
			"url": "http://example.com",
			"content": null,
			"urlSettings": {
				"operation": "GET",
				"encoding": "utf8",
				"headers": {},
				"data": null
			},
			"renderType": "jpg",
			"outputAsJson": false,
			"requestSettings": {
				"ignoreImages": false,
				"disableJavascript": false,
				"userAgent": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/534.34 (KHTML, like Gecko) Safari/534.34 PhantomJS/2.0.0 (PhantomJsCloud.com/2.0.1)",
				"authentication": {
					"userName": "guest",
					"password": "guest"
				},
				"xssAuditingEnabled": false,
				"webSecurityEnabled": false,
				"resourceWait": 15000,
				"resourceTimeout": 35000,
				"maxWait": 35000,
				"waitInterval": 1000,
				"stopOnError": false,
				"resourceModifier": [],
				"customHeaders": {},
				"clearCache": false,
				"clearCookies": false,
				"cookies": [],
				"deleteCookies": []
			},
			"suppressJson": [
				"events.value.resourceRequest.headers",
				"events.value.resourceResponse.headers",
				"frameData.content",
				"frameData.childFrames"
			],
			"renderSettings": {
				"quality": 70,
				"pdfOptions": {
					"border": null,
					"footer": {
						"firstPage": null,
						"height": "1cm",
						"lastPage": null,
						"onePage": null,
						"repeating": "%pageNum%/%numPages%"
					},
					"format": "letter",
					"header": null,
					"height": null,
					"orientation": "portrait",
					"width": null
				},
				"clipRectangle": null,
				"renderIFrame": null,
				"viewport": {
					"height": 1280,
					"width": 1280
				},
				"zoomFactor": 1,
				"passThroughHeaders": false
			},
			"scripts": {
				"domReady": [],
				"loadFinished": []
			}
		}
	],
	"proxy":false
}

csharp code
using (var client = new System.Net.Http.HttpClient())
{
	client.DefaultRequestHeaders.ExpectContinue = false; //REQUIRED! or you will get 502 Bad Gateway errors
	var pageRequestJson = new System.Net.Http.StringContent(System.IO.File.ReadAllText("request.json"));
	var response = client.PostAsync("https://PhantomJScloud.com/api/browser/v2/a-demo-key-with-low-quota-per-ip-address/", pageRequestJson).Result;
	var responseStream = response.Content.ReadAsStreamAsync().Result;
	using (var fileStream = new System.IO.FileStream("content.jpg", System.IO.FileMode.Create))
	{
		responseStream.CopyTo(fileStream);
	}                                         
	Console.WriteLine("*** Headers, pay attention to those starting with 'pjsc-' ***");
	Console.WriteLine(response.Headers);
}

Need more advanced examples?

Check out the Advanced Scenario Samples section of the Docs Index Page for Page Automation, Auto-Login, and more.