C# пример: быстрый старт за 2 минуты
2026-01-24
Этот сниппет демонстрирует, как решить текстовую капчу, используя C# и HttpClient.
Полный пример кода
Скопируйте и вставьте это в ваше консольное приложение:
Console Application
using System;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
const string apiKey = "YOUR_API_KEY";
const string imagePath = "captcha.png";
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
// Prepare multipart form data
await using var stream = File.OpenRead(imagePath);
var content = new MultipartFormDataContent();
content.Add(new StreamContent(stream), "image", Path.GetFileName(imagePath));
// Send request to API
var response = await client.PostAsync(
"http://api.noncaptcha.com/api/json/text",
content
);
// Read and parse result
var jsonResponse = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Status: {response.StatusCode}");
Console.WriteLine($"Response: {jsonResponse}");
if (response.IsSuccessStatusCode)
{
var result = JsonSerializer.Deserialize<TextResponse>(jsonResponse);
Console.WriteLine($"Solved text: {result?.text}");
}
}
// Response model
public class TextResponse
{
public string text { get; set; }
}
}
Парсинг ответа
API возвращает простой JSON объект:
JSON Response
{
"text": "abc123"
}
Вы можете использовать System.Text.Json для десериализации в строго типизированный объект.
Паттерн Async/Await
Современный подход на C# с корректной асинхронностью:
Modern Async Pattern
public class CaptchaSolver
{
private readonly HttpClient _client;
private readonly string _apiKey;
public CaptchaSolver(string apiKey)
{
_apiKey = apiKey;
_client = new HttpClient
{
BaseAddress = new Uri("http://api.noncaptcha.com"),
Timeout = TimeSpan.FromSeconds(30)
};
_client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
}
public async Task<string> SolveTextCaptchaAsync(string imagePath)
{
using var stream = File.OpenRead(imagePath);
var content = new MultipartFormDataContent();
content.Add(new StreamContent(stream), "image", Path.GetFileName(imagePath));
var response = await _client.PostAsync("/api/json/text", content);
if (!response.IsSuccessStatusCode)
{
throw new Exception($"API error: {response.StatusCode}");
}
var json = await response.Content.ReadAsStringAsync();
using var doc = JsonDocument.Parse(json);
return doc.RootElement.GetProperty("text").GetString();
}
public void Dispose() => _client.Dispose();
}
// Usage
using var solver = new CaptchaSolver("YOUR_API_KEY");
var result = await solver.SolveTextCaptchaAsync("captcha.png");
Console.WriteLine($"Result: {result}");
Обработка ошибок
Полный пример с обработкой ошибок:
With Error Handling
try
{
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", "YOUR_API_KEY");
using var stream = File.OpenRead("captcha.png");
var content = new MultipartFormDataContent();
content.Add(new StreamContent(stream), "image", "captcha.png");
var response = await client.PostAsync(
"http://api.noncaptcha.com/api/json/text",
content
);
var result = await response.Content.ReadAsStringAsync();
if (response.StatusCode == System.Net.HttpStatusCode.PaymentRequired)
{
Console.WriteLine("❌ Insufficient balance!");
return;
}
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"❌ API Error: {response.StatusCode}");
Console.WriteLine($"Response: {result}");
return;
}
// Parse JSON response
using var doc = JsonDocument.Parse(result);
var text = doc.RootElement.GetProperty("text").GetString();
Console.WriteLine($"✅ Solved: {text}");
}
catch (FileNotFoundException)
{
Console.WriteLine("❌ Captcha file not found!");
}
catch (HttpRequestException ex)
{
Console.WriteLine($"❌ Network error: {ex.Message}");
}
catch (JsonException ex)
{
Console.WriteLine($"❌ Invalid JSON response: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"❌ Unexpected error: {ex.Message}");
}
Совет:
Для продакшена используйте переиспользуемый экземпляр HttpClient и правильную внедрение зависимостей.