October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
Mountain View desk3 min

Search Google from Java Without an SDK: A SerpApi Quickstart

A direct Java HttpClient example for sending a Google search to SerpApi without its SDK, with safe API-key handling and JSON result parsing.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

You can query Google through SerpApi from Java using the built-in java.net.http.HttpClient; no SerpApi SDK is required. The example below reads your API key from SERPAPI_KEY, sends a URL-encoded Google search request, checks the HTTP response, and prints the first result title when one is available. It expects JSON and uses Gson to parse it.

What the request does

SerpApi accepts a search request with an API key, engine=google, and a query in q. A successful response is JSON containing structured result data, including an organic_results array when organic results are present. This Java example makes the HTTP request directly to SerpApi rather than using its Java wrapper.

Before running it, you need a SerpApi account and API key, a JDK with java.net.http (Java 11 or later), and Gson on your classpath. Create an API key through SerpApi’s Java integration guide. For a quick local run, add Gson to your project using your build tool; the snippet does not add a vendor SDK.

Store the API key outside your code

Set the key in the environment as SERPAPI_KEY before launching Java. For example, in a Unix-like shell:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
export SERPAPI_KEY="your_api_key_here"

On Windows PowerShell, use $env:SERPAPI_KEY="your_api_key_here" in the same session that starts the program. Do not commit a real key to source control. SerpApi’s Java repository specifically advises: “Use an environment variable rather than committing it to source control.” See the official repository’s API key guidance.

Send a Google search from Java

This compact example uses Java’s standard HTTP client, URL-encodes the query, rejects non-success HTTP status codes, and handles an absent or empty organic-results list. The Gson parsing uses JsonObject and JsonArray.

import java.net.URI;
import java.net.URLEncoder;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import com.google.gson.*;

public class Search {
  public static void main(String[] args) throws Exception {
    String key = System.getenv("SERPAPI_KEY");
    if (key == null || key.isBlank()) throw new IllegalStateException("Set SERPAPI_KEY");
    String q = URLEncoder.encode("Java HTTP client", StandardCharsets.UTF_8);
    String url = "https://serpapi.com/search.json?engine=google&q=" + q + "&api_key=" + URLEncoder.encode(key, StandardCharsets.UTF_8);
    HttpRequest request = HttpRequest.newBuilder(URI.create(url)).GET().build();
    HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
    if (response.statusCode() < 200 || response.statusCode() >= 300)
      throw new IllegalStateException("SerpApi returned HTTP " + response.statusCode() + ": " + response.body());
    JsonObject json = JsonParser.parseString(response.body()).getAsJsonObject();
    JsonArray results = json.has("organic_results") ? json.getAsJsonArray("organic_results") : new JsonArray();
    if (results.isEmpty()) System.out.println("No organic results returned.");
    else System.out.println(results.get(0).getAsJsonObject().get("title").getAsString());
  }
}

The endpoint returns JSON, so the example parses the response body rather than scraping HTML. For production code, consider adding a request timeout, handling malformed JSON and API-level error objects, and avoiding logging the full response if it could expose data you do not want in logs.

Change the search and its locale

Replace the example text in URLEncoder.encode("Java HTTP client", ...) with the query you want. URL-encoding matters for spaces and punctuation; do not concatenate an unencoded query into the URL.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

SerpApi’s product page shows additional request parameters such as location, hl (language), gl (country), and google_domain. Add only the parameters relevant to your use case, encoding each value as a query parameter. Consult the Google Search API page for the current endpoint details and supported parameters, since API options can change.

Direct HTTP or the official Java SDK?

Choice What you gain What you take on
Direct HTTP (this example) No SerpApi SDK dependency; direct control over request construction, Java HTTP behavior, and JSON parsing. You write and maintain request encoding, response parsing, and error handling yourself.
Official serpapi-java SDK A vendor-maintained wrapper with structured Gson results and documented Markdown, raw HTML, async search, archive, account, and location operations. Adds a library dependency and uses the SDK’s conventions. The official repository says its current branch is built and tested with JDK 21, and releases target Java 21.

The official integration guide currently documents Gradle dependency com.github.serpapi:serpapi-java:1.2.0; verify the current version and runtime guidance in the integration guide and repository before adopting it. The older google-search-results-java repository is a legacy wrapper; do not mix its dependency instructions with those for the current SDK.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Check current usage limits

SerpApi’s product page, accessed in 2026, displays a free plan with 250 searches per month and paid monthly examples: Starter at $25 for 1,000 searches, Developer at $75 for 5,000, Production at $150 for 15,000, and Big Data at $275 for 30,000. These are page-displayed offers, not guaranteed long-term prices or quotas; check the current product page for availability and terms before choosing a plan.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.