# Java
URL: /docs/examples/java.mdx

Integre a API brapi.dev em suas aplicações Java usando HttpClient. Exemplos práticos para buscar cotações de ações da B3.

***

title: 'Java'
description: >-
Integre a API brapi.dev em suas aplicações Java usando HttpClient. Exemplos
práticos para buscar cotações de ações da B3.
full: false
keywords: brapi, api, java, httpclient, cotações, B3
openGraph:
title: Integração Java - brapi.dev
description: Exemplos de integração usando Java 11+ HttpClient
type: website
locale: pt\_BR
lastUpdated: '2025-10-12T17:30:00.000Z'
lang: pt-BR
-----------

Integre a API brapi.dev em suas aplicações Java usando HttpClient (Java 11+).

## Exemplo Básico

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class BrapiExample {
    public static void main(String[] args) throws Exception {
        String token = "SEU_TOKEN";
        String ticker = "PETR4";
        String url = "https://brapi.dev/api/quote/" + ticker + "?token=" + token;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .GET()
            .build();

        HttpResponse<String> response = client.send(request,
            HttpResponse.BodyHandlers.ofString());

        System.out.println(response.body());
    }
}
```

## Classe Cliente Completa

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class BrapiClient {
    private static final String BASE_URL = "https://brapi.dev/api";
    private final HttpClient httpClient;
    private final String token;
    private final Gson gson;

    public BrapiClient(String token) {
        this.token = token;
        this.httpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();
        this.gson = new Gson();
    }

    public QuoteResponse getQuote(String ticker) throws Exception {
        String url = String.format("%s/quote/%s?token=%s", BASE_URL, ticker, token);
        
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header("User-Agent", "Java BrapiClient/1.0")
            .GET()
            .build();

        HttpResponse<String> response = httpClient.send(request,
            HttpResponse.BodyHandlers.ofString());

        if (response.statusCode() != 200) {
            throw new Exception("HTTP " + response.statusCode());
        }

        return gson.fromJson(response.body(), QuoteResponse.class);
    }

    public static class QuoteResponse {
        public Quote[] results;
        
        public static class Quote {
            public String symbol;
            public String shortName;
            public double regularMarketPrice;
            public double regularMarketChange;
            public double regularMarketChangePercent;
            public String currency;
        }
    }

    public static void main(String[] args) {
        try {
            BrapiClient client = new BrapiClient("SEU_TOKEN");
            QuoteResponse response = client.getQuote("PETR4");
            
            if (response.results != null && response.results.length > 0) {
                QuoteResponse.Quote quote = response.results[0];
                System.out.printf("%s: R$ %.2f%n", quote.symbol, quote.regularMarketPrice);
                System.out.printf("Variação: %.2f%%%n", quote.regularMarketChangePercent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

## Spring Boot

```java
// BrapiService.java
package com.example.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class BrapiService {
    
    @Value("${brapi.token}")
    private String token;
    
    private final RestTemplate restTemplate = new RestTemplate();
    private static final String BASE_URL = "https://brapi.dev/api";
    
    @Cacheable(value = "quotes", key = "#ticker")
    public QuoteResponse getQuote(String ticker) {
        String url = String.format("%s/quote/%s?token=%s", BASE_URL, ticker, token);
        return restTemplate.getForObject(url, QuoteResponse.class);
    }
}

// Controller
package com.example.controller;

import com.example.service.BrapiService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/stock")
public class StockController {
    
    private final BrapiService brapiService;
    
    public StockController(BrapiService brapiService) {
        this.brapiService = brapiService;
    }
    
    @GetMapping("/{ticker}")
    public QuoteResponse getStock(@PathVariable String ticker) {
        return brapiService.getQuote(ticker);
    }
}

// application.properties
// brapi.token=SEU_TOKEN
```

## Próximos Passos

* Explore [outros exemplos](/docs/examples)
* Veja a [documentação completa](/docs)


