-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathApiClient.cs
95 lines (76 loc) · 2.58 KB
/
ApiClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using TwoCaptcha.Exceptions;
namespace TwoCaptcha
{
public class ApiClient
{
/**
* API server
*/
private string baseUrl = "https://2captcha.com/";
/**
* Network client
*/
private readonly HttpClient client = new HttpClient();
public ApiClient()
{
client.BaseAddress = new Uri(baseUrl);
}
public virtual async Task<string> In(Dictionary<string, string> parameters, Dictionary<string, FileInfo> files)
{
var content =
new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture));
foreach (KeyValuePair<string, string> p in parameters)
{
content.Add(new StringContent(p.Value), p.Key);
}
foreach (KeyValuePair<string, FileInfo> f in files)
{
var fileStream = new StreamContent(new MemoryStream(File.ReadAllBytes(f.Value.FullName)));
content.Add(fileStream, f.Key, f.Value.Name);
}
var request = new HttpRequestMessage(HttpMethod.Post, "in.php")
{
Content = content
};
return await Execute(request);
}
public virtual async Task<string> Res(Dictionary<string, string> parameters)
{
var request = new HttpRequestMessage(HttpMethod.Get, "res.php?" + BuildQuery(parameters));
return await Execute(request);
}
private string BuildQuery(Dictionary<string, string> parameters)
{
string query = "";
foreach (KeyValuePair<string, string> p in parameters)
{
if (query.Length > 0)
{
query += "&";
}
query += p.Key + "=" + Uri.EscapeDataString(p.Value);
}
return query;
}
private async Task<string> Execute(HttpRequestMessage request)
{
var response = await client.SendAsync(request);
string body = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
throw new NetworkException("Unexpected response: " + body);
}
if (body.StartsWith("ERROR_"))
{
throw new ApiException(body);
}
return body;
}
}
}