Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/mercadopago/sdk-java/llms.txt

Use this file to discover all available pages before exploring further.

The Mercado Pago Java SDK delegates all HTTP communication through a single pluggable interface — MPHttpClient. The built-in MPDefaultHttpClient is backed by Apache HttpClient 4.x and handles TLS 1.2, connection pooling, keep-alive, retries, and proxy support out of the box. When you need to add middleware (logging, distributed tracing, custom headers) or replace the transport layer entirely, you implement MPHttpClient and register it with MercadoPagoConfig before making any API calls.

MPHttpClient interface

Package: com.mercadopago.net MPHttpClient is the contract that every HTTP transport must satisfy. It defines a single method responsible for the full HTTP lifecycle: building the underlying request from an MPRequest, executing it, and returning an MPResponse.

Method

send(MPRequest request)
MPResponse
Sends the given HTTP request to the Mercado Pago API and returns the response.
  • If the API responds with a status code greater than 299, the implementation must throw an MPApiException containing the full MPResponse.
  • If a transport-level error prevents the request from completing (I/O failure, connection timeout, etc.), throw an MPException.
Throws:
  • MPException — transport-level failure
  • MPApiException — API returned a non-success status code (> 299)

Method signature

MPResponse send(MPRequest request) throws MPException, MPApiException;

Registering a custom implementation

import com.mercadopago.MercadoPagoConfig;

MercadoPagoConfig.setAccessToken("APP_USR-your-access-token");
MercadoPagoConfig.setHttpClient(new CustomHttpClient());
Call setHttpClient before making any API requests. The SDK does not lock the client after first use, so you can swap it at runtime (e.g., in tests).

MPDefaultHttpClient

Package: com.mercadopago.net MPDefaultHttpClient is the SDK’s built-in MPHttpClient implementation. It wraps Apache HttpClient 4.x and is configured with production-grade defaults:
BehaviourDetail
TLSOnly TLSv1.2 is enabled for HTTPS connections.
Connection poolPoolingHttpClientConnectionManager; maximum total and per-route connections controlled by MercadoPagoConfig.getMaxConnections() (default 10).
Connection validationIdle connections are validated after 30 000 ms of inactivity before reuse.
Keep-aliveKeepAliveStrategy parses the server’s Keep-Alive: timeout=N header and converts it to milliseconds; defaults to 10 000 ms when the header is absent.
Automatic retriesUp to 3 retries for failed requests. Non-idempotent requests (POST) are not retried unless you supply a custom HttpRequestRetryHandler.
CookiesDisabled.
RedirectsDisabled.

Transport error mapping

When low-level exceptions escape the underlying HttpClient.execute() call, MPDefaultHttpClient maps them to synthetic HTTP status codes and wraps them in MPApiException:
ExceptionMapped status
ClientProtocolException400 Bad Request
SSLPeerUnverifiedException403 Forbidden
IOException500 Internal Server Error
Any other unexpected exception is re-thrown wrapped in an MPException.

Constructors

MPDefaultHttpClient()
constructor
Constructs a new client with default settings. Internally creates and configures the Apache HttpClient with TLS 1.2, connection pooling, keep-alive, retries, and optional proxy support from MercadoPagoConfig.
MPDefaultHttpClient(HttpClient httpClient)
constructor
deprecated
Protected constructor intended for testing. Accepts an externally created Apache HttpClient. If null is passed, falls back to createHttpClient().

MPRequest

Package: com.mercadopago.net MPRequest is an immutable value object representing a single HTTP request to the Mercado Pago API. Instances are built via the Lombok-generated builder or through the buildRequest factory method, which merges per-request options from MPRequestOptions into the final object.

Fields

uri
String
required
The fully-qualified URI or relative path for the API endpoint (e.g., https://api.mercadopago.com/v1/payments).
method
HttpMethod
required
The HTTP method to use for this request. One of GET, POST, PUT, PATCH, or DELETE.
payload
JsonObject
The JSON request body. null for methods that do not carry a payload (GET, DELETE). Passing a payload with GET or DELETE causes MPMalformedRequestException to be thrown.
headers
Map<String, String>
Custom HTTP headers to include in this request, keyed by header name. Merged with the SDK’s default headers at send time.
queryParams
Map<String, Object>
Query parameters to append to the URI, keyed by parameter name.
accessToken
String
Per-request OAuth access token. When set, overrides the global token from MercadoPagoConfig.getAccessToken().
connectionTimeout
int
Connection timeout in milliseconds for this request. A value of 0 falls back to MercadoPagoConfig.getConnectionTimeout() (default 20 000 ms).
connectionRequestTimeout
int
Timeout in milliseconds for obtaining a connection from the pool. A value of 0 falls back to MercadoPagoConfig.getConnectionRequestTimeout() (default 20 000 ms).
socketTimeout
int
Socket (read) timeout in milliseconds. A value of 0 falls back to MercadoPagoConfig.getSocketTimeout() (default 20 000 ms).

Factory method

public static MPRequest buildRequest(
    String path,
    HttpMethod method,
    JsonObject payload,
    Map<String, Object> queryParams,
    MPRequestOptions requestOptions)
When requestOptions is not null, its custom headers, access token, and timeout values are applied to the resulting request. When requestOptions is null, only path, method, and payload are set.

Idempotency key generation

public String createIdempotencyKey()
Generates a random UUID v4 string suitable for use as the X-Idempotency-Key header. The SDK automatically calls this method and injects the key for POST, PUT, and PATCH requests unless the X-Idempotency-Key header is already present in the request’s headers map.

MPResponse

Package: com.mercadopago.net MPResponse is an immutable value object representing the raw HTTP response returned by the Mercado Pago API. It is created by MPDefaultHttpClient after executing a request, attached to resource objects, and also exposed through MPApiException.getApiResponse() on error paths.

Fields

statusCode
Integer
required
The HTTP status code of the response (e.g., 200, 201, 400). See com.mercadopago.net.HttpStatus for named constants.
headers
Map<String, List<String>>
required
All response headers keyed by header name. Each key maps to a list of values to support HTTP headers that may appear multiple times (e.g., Set-Cookie). Use headers.get("x-request-id") to retrieve the Mercado Pago request identifier for support correlation.
content
String
required
The raw response body as a UTF-8 string. For error responses this is typically a JSON object. May be empty for 204 No Content responses.

Headers constants

Package: com.mercadopago.net
Class: Headers
The Headers class defines string constants for every HTTP header the SDK reads or writes. Use these constants instead of raw strings to avoid typos.
ConstantHeader namePurpose
Headers.AUTHORIZATIONAuthorizationCarries the Bearer access token for authentication.
Headers.CONTENT_TYPEContent-TypeMedia type of the request body — typically application/json.
Headers.ACCEPTAcceptMedia types the client will accept in responses.
Headers.USER_AGENTUser-AgentIdentifies the SDK version and Java runtime.
Headers.IDEMPOTENCY_KEYX-Idempotency-KeyEnsures POST/PUT/PATCH idempotency. Auto-generated unless already present.
Headers.PRODUCT_IDX-Product-IdInternal SDK product identifier (MercadoPagoConfig.PRODUCT_ID).
Headers.TRACKING_IDX-Tracking-IdPlatform and SDK version telemetry (MercadoPagoConfig.TRACKING_ID).
Headers.CORPORATION_IDX-Corporation-IdCorporation identifier set via MercadoPagoConfig.setCorporationId(String).
Headers.INTEGRATOR_IDX-Integrator-IdIntegrator (partner) identifier set via MercadoPagoConfig.setIntegratorId(String).
Headers.PLATFORM_IDX-Platform-IdE-commerce platform identifier set via MercadoPagoConfig.setPlatformId(String).

HttpMethod enum

Package: com.mercadopago.net HttpMethod enumerates the HTTP verbs the SDK supports. It is used in MPRequest and validated by MPDefaultHttpClient before executing any request.
ValueHTTP verbTypical use
GETGETRetrieve a resource — no payload allowed.
POSTPOSTCreate a new resource.
PUTPUTFully replace an existing resource.
PATCHPATCHPartially update an existing resource.
DELETEDELETERemove a resource — no payload allowed.

Proxy configuration

Set an HTTP proxy globally before any API call using MercadoPagoConfig.setProxy(HttpHost). MPDefaultHttpClient picks this up when its internal HttpClient is constructed.
import com.mercadopago.MercadoPagoConfig;
import org.apache.http.HttpHost;

MercadoPagoConfig.setAccessToken("APP_USR-your-access-token");
MercadoPagoConfig.setProxy(new HttpHost("proxy.example.com", 8080));
The proxy is applied to all connections made by MPDefaultHttpClient. If you supply a custom MPHttpClient implementation, you are responsible for reading MercadoPagoConfig.getProxy() and routing traffic accordingly.

Retry handler

By default MPDefaultHttpClient retries failed requests up to 3 times using Apache’s DefaultHttpRequestRetryHandler with non-idempotent retry disabled (POST requests are not retried). To override this behaviour, supply a custom HttpRequestRetryHandler:
import com.mercadopago.MercadoPagoConfig;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;

// Retry up to 5 times, including non-idempotent methods
HttpRequestRetryHandler retryHandler =
    new DefaultHttpRequestRetryHandler(5, true);

MercadoPagoConfig.setRetryHandler(retryHandler);
Set the retry handler before the first API call so that MPDefaultHttpClient picks it up during construction.

Implementing a custom MPHttpClient

The most common reasons to provide a custom MPHttpClient are:
  • Distributed tracing — inject trace IDs (e.g., OpenTelemetry) into every outbound request
  • Structured request/response logging — capture full payloads for audit purposes
  • Alternative HTTP libraries — replace Apache HttpClient with OkHttp or the Java 11 HttpClient
  • Testing — record and replay requests without hitting the live API
The example below wraps MPDefaultHttpClient to add a correlation header and structured logging on every request:
import com.mercadopago.MercadoPagoConfig;
import com.mercadopago.exceptions.MPApiException;
import com.mercadopago.exceptions.MPException;
import com.mercadopago.net.Headers;
import com.mercadopago.net.MPDefaultHttpClient;
import com.mercadopago.net.MPHttpClient;
import com.mercadopago.net.MPRequest;
import com.mercadopago.net.MPResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class TracingHttpClient implements MPHttpClient {

    private final MPDefaultHttpClient delegate = new MPDefaultHttpClient();

    @Override
    public MPResponse send(MPRequest request) throws MPException, MPApiException {
        // Inject a per-request trace ID for distributed tracing
        String traceId = UUID.randomUUID().toString();

        // MPRequest is immutable; rebuild headers with the extra entry
        Map<String, String> enrichedHeaders = new HashMap<>(request.getHeaders());
        enrichedHeaders.put("X-Trace-Id", traceId);

        MPRequest enrichedRequest = MPRequest.builder()
            .uri(request.getUri())
            .method(request.getMethod())
            .payload(request.getPayload())
            .headers(enrichedHeaders)
            .queryParams(request.getQueryParams())
            .accessToken(request.getAccessToken())
            .connectionTimeout(request.getConnectionTimeout())
            .connectionRequestTimeout(request.getConnectionRequestTimeout())
            .socketTimeout(request.getSocketTimeout())
            .build();

        System.out.printf("[HTTP] %s %s traceId=%s%n",
            request.getMethod(), request.getUri(), traceId);

        MPResponse response = delegate.send(enrichedRequest);

        System.out.printf("[HTTP] status=%d traceId=%s%n",
            response.getStatusCode(), traceId);

        return response;
    }
}
Register the custom client once at application startup:
MercadoPagoConfig.setAccessToken("APP_USR-your-access-token");
MercadoPagoConfig.setHttpClient(new TracingHttpClient());
The SDK automatically generates and injects a UUID X-Idempotency-Key header for POST, PUT, and PATCH requests. If your custom client or enriched headers already contain an X-Idempotency-Key entry, the SDK will use your value unchanged — it never overwrites a key that is already present.

Build docs developers (and LLMs) love