BuyProxy logo
Log inSign up

SDKs

Java SDK

The official Java library for BuyProxy: generate residential, mobile, ISP and datacenter proxies, check bandwidth, buy more by card or crypto, and run a reseller business. Java 17+. Immutable record models with @Nullable annotations; built on the JDK's java.net.http.HttpClient and Jackson.

  • Immutable record models, @Nullable-annotated for NullAway/Kotlin

  • Unchecked, typed exceptions — compose cleanly with streams and lambdas

  • Automatic retries with back-off for rate limits and transient errors

  • ProxyEndpoint.httpClientBuilder() returns a java.net.http.HttpClient already routed through the proxy

Source, issues and releases: github.com/DishantSinghDev2/buyproxy-java

Installation

Maven

xml
<dependency>
  <groupId>org.buyproxy</groupId>
  <artifactId>buyproxy</artifactId>
  <version>1.0.0</version>
</dependency>

Gradle

kotlin
implementation("org.buyproxy:buyproxy:1.0.0")

Java 17+. Depends only on Jackson (jackson-databind) and jspecify annotations.

Authentication

Create an API key under Dashboard → API keys — personal keys start bp_key_, reseller keys bp_live_. The SDK reads BUYPROXY_API_KEY from the environment automatically; you can also pass the key explicitly. A missing key fails immediately with an authentication error, without a network call.

java
// 1. Environment variable (recommended)
BuyProxy bp = BuyProxy.builder().build();

// 2. Explicit key, e.g. from Spring config / a secrets manager
BuyProxy bp = BuyProxy.builder().apiKey(secret).build();

// 3. Which kind of key is it?
System.out.println(bp.keyKind()); // "personal" | "reseller" | null
Never put an API key in client-side code, a mobile app, a public repository or a log line. Revoke a leaked key from the dashboard and create a new one.

Quick start

java
import org.buyproxy.*;

BuyProxy bp = BuyProxy.builder().apiKey(System.getenv("BUYPROXY_API_KEY")).build(); // or omit — reads BUYPROXY_API_KEY

var plan = bp.plans().list().get(0);
GeneratedProxies result = bp.plans().generate(plan.id(),
        GenerateParams.create().country("US").city("Austin").count(5));

System.out.println(result.get(0).url()); // http://user-country-us-city-austin:pass@gw.buyproxy.org:6969

Add .stickyMinutes(10) to keep the same IP for ten minutes, or .protocol("socks5") for SOCKS5.

Generating proxies

Generation is free and instant — bandwidth is only consumed when traffic flows through a proxy. Every parameter is optional; omit one and the API's default applies. (Names follow each language's conventions, e.g. stickyMinutes / sticky_minutes / StickyMinutes.)

ParameterTypeWhat it does
protocol"http" \"socks5"Proxy protocol. Default http (which also carries HTTPS). Check plan.generate.protocols for what a product supports
countinteger 1–1000How many proxy lines to return. Default 1
countryISO 3166-1 alpha-2e.g. US, DE, JP. Omit for a worldwide IP
statestringState or region, where the product supports it
citystringCity, where the product supports it
ispstringNetwork / carrier, where the product supports it
stickyMinutesintegerKeep the same IP for this many minutes. Omit for a fresh IP on every request. The maximum is plan.generate.maxStickyMinutes; 0 there means the product has no sticky sessions

Each returned line is username:password@host:port with your targeting encoded in the username. Lines are on-demand and not persistent — generate fresh ones when you need them instead of storing them, because credentials can rotate when the pool moves.

java
// Country, state and city — what a plan supports is in plan.generate().targeting()
bp.plans().generate(plan.id(), GenerateParams.create().country("US").state("California").city("Los Angeles"));

// Sticky session: keep one IP for 30 minutes (max is plan.generate().maxStickyMinutes())
bp.plans().generate(plan.id(), GenerateParams.create().country("DE").stickyMinutes(30));

// SOCKS5 instead of HTTP
bp.plans().generate(plan.id(), GenerateParams.create().protocol("socks5").count(10));

// Bulk: up to 1000 lines per call
GeneratedProxies result = bp.plans().generate(plan.id(), GenerateParams.create().count(1000));
Files.write(Path.of("proxies.txt"), result.lines());

Every top-up and allocation call takes a product key. Live prices come from the catalog call, so you never hard-code a rate.

KeyProductMin orderBest for
residentialCore Residential1 GBEveryday rotating residential IPs with country targeting
premiumPremium Residential2 GBCity-level targeting, sticky sessions and priority routing
ispISP Rotating1 GBDatacenter speed with ISP-grade trust
mobileMobile Proxies1 GBReal carrier IPs for mobile-only targets
ipv4Datacenter IPv41 GBFast, cheap per-GB datacenter traffic
ipv6IPv6 Proxies1 GBHuge address diversity at the lowest per-GB rate

Pay-as-you-go top-ups of 100 GB or more include a 10% volume bonus, and a single order is capped at 10,000 GB.

Using the proxies with your stack

Each generated proxy is a small object (host, port, username, password, protocol) with helpers that return exactly what common clients expect, so you never hand-build a proxy URL or worry about percent-encoding special characters in a password.

java.net.http.HttpClient

java
HttpClient http = result.get(0).httpClientBuilder().build();
String ip = http.send(HttpRequest.newBuilder(URI.create("http://api.ipify.org")).build(), BodyHandlers.ofString()).body();
The JDK disables Basic auth for HTTPS tunnelling by default. To reach https:// targets through an HTTP proxy, start the JVM with -Djdk.http.auth.tunneling.disabledSchemes="".

HttpURLConnection

java
HttpURLConnection conn = (HttpURLConnection) new URL("http://api.ipify.org").openConnection(result.get(0).toNetProxy());

Spring Boot

java
@Configuration
class BuyProxyConfig {
    @Bean
    BuyProxy buyProxy(@Value("${buyproxy.api-key}") String key) {
        return BuyProxy.builder().apiKey(key).build();
    }
}

Selenium / Playwright

java
// Selenium: new org.openqa.selenium.Proxy().setHttpProxy(p.host() + ":" + p.port())
// Playwright: new Browser.NewContextOptions().setProxy(new Proxy(p.server()).setUsername(p.username()).setPassword(p.password()))

Account, balances & history

Read-only calls for building dashboards, alerts and pre-flight checks. balances is the one to watch: it shows spendable GB per product, including GB from a payment that's still being added (pending).

java
Catalog catalog = bp.products().list();            // product keys & live prices — no API key needed
var account = bp.account().get();                   // email, plan, lifetime GB
List<Balance> balances = bp.balances().list();      // spendable GB per product (+ GB still arriving)
List<Plan> plans = bp.plans().list();               // plan ids and what each can generate
List<Transaction> history = bp.transactions().list(20);

Buying bandwidth

  1. Call the top-up method — it returns a hosted payment URL and a transaction id. Card payments are processed by Stripe Checkout; crypto by an invoice page.
  2. Send your user (or yourself) to that URL to pay.
  3. Poll the transaction (or use the SDK's wait helper) until status is succeeded or failed. Crypto payments are checked live on every poll, so they settle even if a webhook is delayed.
  4. The GB shows up under balances within seconds — pendingGb while it's arriving, activeGb once it's live.

Plans are subscriptions billed monthly or yearly by card (crypto only covers pay-as-you-go top-ups). If the account already has a subscription, the call returns the subscription settings page as the URL and a null transaction id — switching plans is prorated there, and you can't accidentally subscribe twice.

java
// Buy 10 GB of Core Residential by card — send the customer to payUrl
CardCheckout checkout = bp.topup().card(CardCheckoutParams.topup("residential", 10));
System.out.println(checkout.payUrl());

// Or subscribe to a plan (monthly or yearly)
bp.topup().card(CardCheckoutParams.plan("pro", "year"));

// Crypto (pay-as-you-go top-ups only)
bp.topup().crypto("residential", 50);

// Wait for the payment to settle — GB appears on bp.balances().list() right after
Transaction tx = bp.transactions().await(checkout.transactionId(), Duration.ofSeconds(3), Duration.ofMinutes(10));

Card payments are processed by Stripe; crypto top-ups are pay-as-you-go only. Subscriptions can be managed or cancelled from Dashboard → Billing.

Reseller API

The reseller API lets you build a proxy product on top of BuyProxy. The flow is always the same:

  1. Fund your pool — buy GB per product into your reseller pool by card or crypto. Pool GB is priced like a normal top-up (including the volume bonus), fixed at purchase time.
  2. Create a customer — an isolated sub-account with its own credentials and no bandwidth. Store the returned username.
  3. Allocate — move whole GB of one product from your pool onto that customer, with an idempotency key. The first allocation of a product creates the plan; later ones add to it.
  4. Generate — produce proxy lines for the customer from their plan id (found on the customer record), with all the usual targeting options.
  5. Monitor — read the customer's usage (remaining, used, total per plan, plus any GB still arriving) to bill or alert.
  6. Suspend / reactivate — a suspended customer can't generate new lines (403). Lines already handed out may keep working until they rotate, so stop distributing them at the same time. You can also rename a customer.

Allocated GB can't be moved back to the pool, so allocate what a customer has paid for.

java
BuyProxy reseller = BuyProxy.builder().apiKey("bp_live_…").build();

reseller.reseller().pool().topupCard("residential", 500);                 // buy into your pool
Customer customer = reseller.reseller().customers().create("Acme Inc");   // isolated sub-account

reseller.reseller().customers().allocate(customer.username(), "residential", 20, "order-1042"); // idempotency key → safe to retry

var detail = reseller.reseller().customers().get(customer.username());
GeneratedProxies result = reseller.reseller().customers()
        .generate(customer.username(), detail.plans().get(0).id(), GenerateParams.create().country("DE"));

reseller.reseller().customers().update(customer.username(), null, "suspended");

Allocating bandwidth to a customer moves real GB, so it accepts an idempotency key. Send the same key twice and the second call moves nothing and returns alreadyApplied: true with the same result — safe to retry after a timeout or crash.

Use a value you can derive again from your own data (an order id, an invoice number), not a random value created per attempt. Keys are scoped to your account and may be up to 200 characters.

Errors & retries

Every non-success response becomes a typed error carrying the HTTP status and the API's own message, so you can branch on the failure instead of parsing strings.

HTTPExceptionMeaning
400BuyProxyException.ValidationA parameter was missing or invalid
401BuyProxyException.AuthenticationMissing or invalid API key (also thrown locally when no key is set)
402BuyProxyException.InsufficientBandwidthEmpty reseller pool, or a plan with no GB left
403BuyProxyException.PermissionDeniedSuspended account/customer, or the plan doesn't include this endpoint
404BuyProxyException.NotFoundPlan, customer or transaction not found on this account
429BuyProxyException.RateLimitOver 60 requests/minute — retryAfterSeconds()
5xxBuyProxyException.ServerBuyProxy or an upstream provider is unavailable
—BuyProxyException.ConnectionNo response (DNS, reset, timeout, offline)
java
try {
    bp.plans().generate(planId);
} catch (BuyProxyException.InsufficientBandwidth e) {
    System.out.println("Out of GB — top up first");
} catch (BuyProxyException.RateLimit e) {
    System.out.println("Slow down; retry in " + e.retryAfterSeconds() + "s");
} catch (BuyProxyException.Authentication e) {
    System.out.println("Check your API key");
}

Every exception extends BuyProxyException and exposes status() and body().

Every SDK retries for you, with the same rules:

  • Rate limits (`429`) are always retried, waiting for the Retry-After the API sends (capped at 30 s) or an exponential back-off with jitter.
  • Reads (GET) are also retried on 502/503/504 and on network failures.
  • Writes are not retried on server errors — a repeated checkout or allocation must never double-charge — unless you attach an idempotency key (see below), which makes the retry provably safe.
  • The default is 2 retries; set it to 0 to turn retries off. After the last attempt you get the typed error.

The API allows 60 requests per minute per key. Batch with count (up to 1000 lines per call) rather than looping over single-proxy calls.

Configuration

java
BuyProxy.builder()
    .apiKey("bp_key_…")                        // default: $BUYPROXY_API_KEY
    .baseUrl("https://www.buyproxy.org")
    .timeout(Duration.ofSeconds(30))
    .maxRetries(2)                              // 429s always; 5xx only for safe requests
    .httpClient(myHttpClient)                   // bring your own java.net.http.HttpClient
    .build();

Concurrency

java
// The client is thread-safe. On Java 21, virtual threads make fan-out trivial
try (var pool = Executors.newVirtualThreadPerTaskExecutor()) {
    var futures = plans.stream()
            .map(p -> pool.submit(() -> bp.plans().generate(p.id(), GenerateParams.create().count(10))))
            .toList();
    for (var f : futures) f.get();
}

Testing your code

You don't need a real account or network to unit-test code that uses the SDK — inject a fake transport. This is how the SDK's own test suite works.

java
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", ex -> {
    byte[] body = "{\"lines\":[\"u:p@gw.buyproxy.org:6969\"]}".getBytes(StandardCharsets.UTF_8);
    ex.getResponseHeaders().add("Content-Type", "application/json");
    ex.sendResponseHeaders(200, body.length);
    ex.getResponseBody().write(body);
    ex.close();
});
server.start();

BuyProxy bp = BuyProxy.builder().apiKey("bp_key_test")
        .baseUrl("http://127.0.0.1:" + server.getAddress().getPort()).build();
assertEquals("gw.buyproxy.org", bp.plans().generate("plan_1").get(0).host());

API reference

Every method maps one-to-one onto a documented REST endpoint.

CapabilityCall
Catalog & pricesbp.products().list()
Accountbp.account().get()
Spendable GB per productbp.balances().list()
Plansbp.plans().list()
Generate proxiesbp.plans().generate(planId, params)
Card checkoutbp.topup().card(params)
Crypto checkoutbp.topup().crypto(product, gb)
Paymentsbp.transactions().list/get/await
Create an accountbp.auth().signup/verifyOtp/resendOtp
Reseller summarybp.reseller().me()
Customersbp.reseller().customers().list/create/get/update/usage/allocate/generate
Reseller poolbp.reseller().pool().get/topupCard/topupCrypto

Notes

  • All exceptions are unchecked and extend BuyProxyException (with status() and body()).

  • ProxyEndpoint.httpClientBuilder() returns a java.net.http.HttpClient.Builder already routed through the proxy.

  • Models are records, so they work with pattern matching and serialise cleanly with Jackson.

Developing the SDK

bash
mvn verify

Was this page helpful?