Skip to content

Commit d266769

Browse files
authored
Merge pull request #149 from Atvaark/cs_httpclient_feature
Add C# HttpClient target client
2 parents cc8e368 + 48e733a commit d266769

19 files changed

+448
-1
lines changed

src/targets/csharp/httpclient.js

Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
'use strict'
2+
3+
var CodeBuilder = require('../../helpers/code-builder')
4+
5+
function getDecompressionMethods (source) {
6+
var acceptEncoding = source.allHeaders['accept-encoding']
7+
if (!acceptEncoding) {
8+
return [] // no decompression
9+
}
10+
11+
var supportedMethods = {
12+
gzip: 'DecompressionMethods.GZip',
13+
deflate: 'DecompressionMethods.Deflate'
14+
}
15+
var methods = []
16+
acceptEncoding.split(',').forEach(function (encoding) {
17+
var match = /\s*([^;\s]+)/.exec(encoding)
18+
if (match) {
19+
var method = supportedMethods[match[1]]
20+
if (method) {
21+
methods.push(method)
22+
}
23+
}
24+
})
25+
26+
return methods
27+
}
28+
29+
module.exports = function (source, options) {
30+
var indentation = ' '
31+
var code = new CodeBuilder(indentation)
32+
33+
var clienthandler = ''
34+
var cookies = !!source.allHeaders.cookie
35+
var decompressionMethods = getDecompressionMethods(source)
36+
if (cookies || decompressionMethods.length) {
37+
clienthandler = 'clientHandler'
38+
code.push('var clientHandler = new HttpClientHandler')
39+
code.push('{')
40+
if (cookies) {
41+
// enable setting the cookie header
42+
code.push(1, 'UseCookies = false,')
43+
}
44+
if (decompressionMethods.length) {
45+
// enable decompression for supported methods
46+
code.push(1, 'AutomaticDecompression = %s,', decompressionMethods.join(' | '))
47+
}
48+
code.push('};')
49+
}
50+
51+
code.push('var client = new HttpClient(%s);', clienthandler)
52+
53+
code.push('var request = new HttpRequestMessage')
54+
code.push('{')
55+
56+
var methods = [ 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS', 'TRACE' ]
57+
var method = source.method.toUpperCase()
58+
if (method && (methods.indexOf(method) !== -1)) {
59+
// buildin method
60+
method = `HttpMethod.${method[0]}${method.substring(1).toLowerCase()}`
61+
} else {
62+
// custom method
63+
method = `new HttpMethod("${method}")`
64+
}
65+
code.push(1, 'Method = %s,', method)
66+
67+
code.push(1, 'RequestUri = new Uri("%s"),', source.fullUrl)
68+
69+
var headers = Object.keys(source.allHeaders).filter(function (header) {
70+
switch (header) {
71+
case 'content-type':
72+
case 'content-length':
73+
case 'accept-encoding':
74+
// skip these headers
75+
return false
76+
default:
77+
return true
78+
}
79+
})
80+
if (headers.length) {
81+
code.push(1, 'Headers =')
82+
code.push(1, '{')
83+
headers.forEach(function (key) {
84+
code.push(2, '{ "%s", "%s" },', key, source.allHeaders[key])
85+
})
86+
code.push(1, '},')
87+
}
88+
89+
if (source.postData.text) {
90+
const contentType = source.postData.mimeType
91+
switch (contentType) {
92+
case 'application/x-www-form-urlencoded':
93+
code.push(1, 'Content = new FormUrlEncodedContent(new Dictionary<string, string>')
94+
code.push(1, '{')
95+
source.postData.params.forEach(function (param) {
96+
code.push(2, '{ "%s", "%s" },', param.name, param.value)
97+
})
98+
code.push(1, '}),')
99+
break
100+
case 'multipart/form-data':
101+
code.push(1, 'Content = new MultipartFormDataContent')
102+
code.push(1, '{')
103+
source.postData.params.forEach(function (param) {
104+
code.push(2, 'new StringContent(%s)', JSON.stringify(param.value || ''))
105+
code.push(2, '{')
106+
code.push(3, 'Headers =')
107+
code.push(3, '{')
108+
if (param.contentType) {
109+
code.push(4, 'ContentType = new MediaTypeHeaderValue("%s"),', param.contentType)
110+
}
111+
code.push(4, 'ContentDisposition = new ContentDispositionHeaderValue("form-data")')
112+
code.push(4, '{')
113+
code.push(5, 'Name = "%s",', param.name)
114+
if (param.fileName) {
115+
code.push(5, 'FileName = "%s",', param.fileName)
116+
}
117+
code.push(4, '}')
118+
code.push(3, '}')
119+
code.push(2, '},')
120+
})
121+
122+
code.push(1, '},')
123+
break
124+
default:
125+
code.push(1, 'Content = new StringContent(%s)', JSON.stringify(source.postData.text || ''))
126+
code.push(1, '{')
127+
code.push(2, 'Headers =')
128+
code.push(2, '{')
129+
code.push(3, 'ContentType = new MediaTypeHeaderValue("%s")', contentType)
130+
code.push(2, '}')
131+
code.push(1, '}')
132+
break
133+
}
134+
}
135+
code.push('};')
136+
137+
// send and read response
138+
code.push('using (var response = await client.SendAsync(request))')
139+
code.push('{')
140+
code.push(1, 'response.EnsureSuccessStatusCode();')
141+
code.push(1, 'var body = await response.Content.ReadAsStringAsync();')
142+
code.push(1, 'Console.WriteLine(body);')
143+
code.push('}')
144+
145+
return code.join()
146+
}
147+
148+
module.exports.info = {
149+
key: 'httpclient',
150+
title: 'HttpClient',
151+
link: 'https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient',
152+
description: '.NET Standard HTTP Client'
153+
}

src/targets/csharp/index.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,6 @@ module.exports = {
88
default: 'restsharp'
99
},
1010

11-
restsharp: require('./restsharp')
11+
restsharp: require('./restsharp'),
12+
httpclient: require('./httpclient')
1213
}

test/fixtures/available-targets.json

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,12 @@
230230
"title": "RestSharp",
231231
"link": "http://restsharp.org/",
232232
"description": "Simple REST and HTTP API Client for .NET"
233+
},
234+
{
235+
"key": "httpclient",
236+
"title": "HttpClient",
237+
"link": "https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient",
238+
"description": ".NET Standard HTTP Client"
233239
}
234240
]
235241
},
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
var client = new HttpClient();
2+
var request = new HttpRequestMessage
3+
{
4+
Method = HttpMethod.Post,
5+
RequestUri = new Uri("http://mockbin.com/har"),
6+
Content = new FormUrlEncodedContent(new Dictionary<string, string>
7+
{
8+
{ "foo", "bar" },
9+
{ "hello", "world" },
10+
}),
11+
};
12+
using (var response = await client.SendAsync(request))
13+
{
14+
response.EnsureSuccessStatusCode();
15+
var body = await response.Content.ReadAsStringAsync();
16+
Console.WriteLine(body);
17+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
var client = new HttpClient();
2+
var request = new HttpRequestMessage
3+
{
4+
Method = HttpMethod.Post,
5+
RequestUri = new Uri("http://mockbin.com/har"),
6+
Content = new StringContent("{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":{}}],\"boolean\":false}")
7+
{
8+
Headers =
9+
{
10+
ContentType = new MediaTypeHeaderValue("application/json")
11+
}
12+
}
13+
};
14+
using (var response = await client.SendAsync(request))
15+
{
16+
response.EnsureSuccessStatusCode();
17+
var body = await response.Content.ReadAsStringAsync();
18+
Console.WriteLine(body);
19+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
var clientHandler = new HttpClientHandler
2+
{
3+
UseCookies = false,
4+
};
5+
var client = new HttpClient(clientHandler);
6+
var request = new HttpRequestMessage
7+
{
8+
Method = HttpMethod.Post,
9+
RequestUri = new Uri("http://mockbin.com/har"),
10+
Headers =
11+
{
12+
{ "cookie", "foo=bar; bar=baz" },
13+
},
14+
};
15+
using (var response = await client.SendAsync(request))
16+
{
17+
response.EnsureSuccessStatusCode();
18+
var body = await response.Content.ReadAsStringAsync();
19+
Console.WriteLine(body);
20+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
var client = new HttpClient();
2+
var request = new HttpRequestMessage
3+
{
4+
Method = new HttpMethod("PROPFIND"),
5+
RequestUri = new Uri("http://mockbin.com/har"),
6+
};
7+
using (var response = await client.SendAsync(request))
8+
{
9+
response.EnsureSuccessStatusCode();
10+
var body = await response.Content.ReadAsStringAsync();
11+
Console.WriteLine(body);
12+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
var clientHandler = new HttpClientHandler
2+
{
3+
UseCookies = false,
4+
};
5+
var client = new HttpClient(clientHandler);
6+
var request = new HttpRequestMessage
7+
{
8+
Method = HttpMethod.Post,
9+
RequestUri = new Uri("http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value"),
10+
Headers =
11+
{
12+
{ "cookie", "foo=bar; bar=baz" },
13+
{ "accept", "application/json" },
14+
},
15+
Content = new FormUrlEncodedContent(new Dictionary<string, string>
16+
{
17+
{ "foo", "bar" },
18+
}),
19+
};
20+
using (var response = await client.SendAsync(request))
21+
{
22+
response.EnsureSuccessStatusCode();
23+
var body = await response.Content.ReadAsStringAsync();
24+
Console.WriteLine(body);
25+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
var client = new HttpClient();
2+
var request = new HttpRequestMessage
3+
{
4+
Method = HttpMethod.Get,
5+
RequestUri = new Uri("http://mockbin.com/har"),
6+
Headers =
7+
{
8+
{ "accept", "application/json" },
9+
{ "x-foo", "Bar" },
10+
},
11+
};
12+
using (var response = await client.SendAsync(request))
13+
{
14+
response.EnsureSuccessStatusCode();
15+
var body = await response.Content.ReadAsStringAsync();
16+
Console.WriteLine(body);
17+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
var client = new HttpClient();
2+
var request = new HttpRequestMessage
3+
{
4+
Method = HttpMethod.Get,
5+
RequestUri = new Uri("https://mockbin.com/har"),
6+
};
7+
using (var response = await client.SendAsync(request))
8+
{
9+
response.EnsureSuccessStatusCode();
10+
var body = await response.Content.ReadAsStringAsync();
11+
Console.WriteLine(body);
12+
}

0 commit comments

Comments
 (0)