Stock Price Tracker Java, API
👤 Sharing: AI
```java
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.Scanner;
public class StockPriceTracker {
private static final String API_KEY = "YOUR_API_KEY"; // Replace with your API key
private static final String API_URL = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=%s&apikey=%s";
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter stock symbol (or 'exit' to quit): ");
String symbol = scanner.nextLine().toUpperCase();
if (symbol.equalsIgnoreCase("exit")) {
break;
}
try {
double price = getStockPrice(symbol);
System.out.println("Current price of " + symbol + ": " + price);
} catch (IOException | InterruptedException e) {
System.err.println("Error fetching stock price for " + symbol + ": " + e.getMessage());
}
}
System.out.println("Exiting Stock Price Tracker.");
scanner.close();
}
public static double getStockPrice(String symbol) throws IOException, InterruptedException {
String url = String.format(API_URL, symbol, API_KEY);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new IOException("API request failed with status code: " + response.statusCode());
}
String responseBody = response.body();
//System.out.println("API Response: " + responseBody); //For debugging
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(responseBody, JsonObject.class);
if (jsonObject != null && jsonObject.has("Global Quote")) {
JsonObject globalQuote = jsonObject.getAsJsonObject("Global Quote");
if (globalQuote != null && globalQuote.has("05. price")) {
String priceString = globalQuote.get("05. price").getAsString();
try {
return Double.parseDouble(priceString);
} catch (NumberFormatException e) {
throw new IOException("Invalid price format received from API: " + priceString);
}
} else {
throw new IOException("Price data not found in API response for " + symbol);
}
} else {
throw new IOException("Global Quote data not found in API response for " + symbol);
}
}
}
```
👁️ Viewed: 9
Comments