Direct answer: add headers to the Java request with HttpRequest.Builder.header(name, value) (or setHeader when replacing an existing value). That authenticates the screenshot API call itself. If the rendered page also needs a header, such as an API token accepted by the target website, pass it through the screenshot provider’s documented target-page header option. The two requests are separate; a header added in Java is not automatically forwarded by the provider’s browser.
Understand the two HTTP requests
A hosted screenshot normally has two HTTP transactions:
- Java to the screenshot service: your application sends an API key, authorization header, URL and rendering options.
- Rendering browser to the target site: the provider’s browser navigates to the URL and downloads the document, scripts, stylesheets and images.
Headers on the first transaction do not become headers on the second. Configure each boundary independently. The provider must explicitly document a target-page header field; otherwise, your Java authorization header only authenticates your account with the screenshot service.
Which header belongs where?
| Need | Where to configure it | Typical example |
|---|---|---|
| Authorize your screenshot API call | Java HttpRequest headers |
Authorization: Bearer … |
| Tell the API which page to render | API URL parameter or JSON field | url |
| Authorize the target page | Provider’s documented target-page header option | X-Preview-Token: … |
| Restore a browser session | Provider’s cookie option | session=… |
Use only credentials and sites you are authorized to access. Treat tokens, cookies and captured images as secrets, and keep them out of public URLs, source control and request logs.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problemsAdd headers with Java 11 or later
Java’s built-in java.net.http client adds a name/value pair with header. Oracle describes it as adding the given name-value pair to the request’s headers. Use setHeader when you want to replace an existing value rather than add another value for the same name. Invalid names or values can be rejected by the implementation.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class ScreenshotRequest {
public static void main(String[] args) throws Exception {
String apiToken = System.getenv("SCREENSHOT_API_TOKEN");
URI endpoint = URI.create("https://api.example.com/v1/screenshot");
HttpRequest request = HttpRequest.newBuilder(endpoint)
.timeout(Duration.ofSeconds(90))
.header("Authorization", "Bearer " + apiToken)
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{"url":"https://example.com"}"))
.build();
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(20))
.build();
HttpResponse<String> response = client.send(
request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
}
}
The Authorization, Accept and Content-Type lines above apply to the API request. They do not configure the browser that visits https://example.com. Consult your provider’s current API documentation for its endpoint, body schema and target-page header syntax. Oracle’s module documentation is at https://docs.oracle.com/en/java/javase/26/docs/api/java.net.http/module-summary.html.
Pass a header to the target page
Providers expose this feature differently. ScreenshotAPI.net documents a repeatable header option in Name: value form and says it is sent only on requests to the target host. Its POST format also supports a headers object. A Java call can therefore put the target header in the provider’s request body, while putting API authentication in Java’s own headers.
Rank #2
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class TargetHeaderScreenshot {
public static void main(String[] args) throws Exception {
String providerToken = System.getenv("PROVIDER_TOKEN");
String pageToken = System.getenv("PAGE_TOKEN");
String json = "{" +
""url":"https://portal.example.com/report"," +
""headers":{" +
""X-Preview-Token":"" + escapeJson(pageToken) + """ +
"}" +
"}";
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://screenshot-api.net/your-endpoint"))
.timeout(Duration.ofSeconds(90))
.header("Authorization", "Bearer " + providerToken)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> response = HttpClient.newHttpClient().send(
request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() < 200 || response.statusCode() >= 300) {
throw new IllegalStateException("Screenshot API returned " + response.statusCode());
}
System.out.println(response.body());
}
private static String escapeJson(String value) {
return value.replace("\", "\\").replace(""", "\"");
}
}
Do not copy this endpoint or field names blindly: verify the provider’s current contract. ScreenshotAPI.net’s documentation, including its Java API-call example and final-page status information, is at https://screenshot-api.net/docs. If a provider offers only a URL parameter, URL-encode it and understand that URLs can appear in logs, browser history and proxy telemetry; a POST body is generally preferable for secrets.
Recommended Free Tools
Headers versus cookies
A target header works only when the site’s authentication layer accepts that header on the document request and any required subrequests. Some applications require a session cookie, CSRF state or a JavaScript login flow instead. ScreenshotOne’s authenticated-pages guide covers both custom token headers and cookie-based authentication: https://screenshotone.com/docs/guides/authenticated-pages/. Choose the mechanism the target application actually uses, and check whether the provider limits headers to the target host so credentials are not sent to third-party resources.
Java’s restricted headers
The JDK controls several protocol-sensitive headers. Oracle lists connection, content-length, expect, host and upgrade as restricted by default. Your code may throw an exception when trying to set one, or the client may manage it itself.
The jdk.httpclient.allowRestrictedHeaders system property can override some restrictions, but the JDK documentation says it is intended for testing and warns of protocol errors or undefined behavior. Do not make it a routine production workaround. Some restrictions, including certain Authorization cases when an authenticator is configured, cannot be overridden by that property. Prefer provider-supported fields and let HttpClient generate transport headers.
End-to-end troubleshooting
401 or 403 from the screenshot API
- Check the Java-to-provider authorization header, token scope and expiration.
- Confirm you are calling the correct regional or API version endpoint.
- Log the status code and a redacted response body, never the token.
The image shows a login or access-denied page
- Verify the target header is in the provider’s documented render option, not only in Java’s request headers.
- Check exact spelling, capitalization, prefix and value format expected by the target application.
- Use a cookie option if the application authenticates sessions rather than bearer headers.
- Confirm the supplied credential is valid for the target host and has permission to view that page.
Header appears on the wrong requests
Check the provider’s scope guarantee. ScreenshotAPI.net states that its header option is sent only to requests to the target host. If your provider does not document host scoping, avoid sending a secret header to pages that load third-party origins.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Java rejects the header
Inspect the exception for an invalid name, illegal value or restricted name. Remove line breaks and control characters, avoid manually setting Host or Content-Length, and use setHeader only when replacement semantics are intended. Treat the restricted-header system property as a test-only diagnostic, not a deployment fix.
Rank #4
The request succeeds but content is stale or incomplete
- Confirm the target header reaches the final document, not just an API metadata request.
- Use the provider’s wait-for-selector, delay or network-idle setting when authentication redirects or client rendering is asynchronous.
- Inspect the final page status or request identifier when available. ScreenshotAPI.net documents a page-status field and response header that help separate authentication failures from rendering failures.
- Check whether caching is returning an earlier authenticated or unauthenticated result.
Alternative request styles
The same separation applies whether you use Java’s client directly, an SDK or another HTTP library: API credentials belong to the provider request; target credentials belong to the provider’s render configuration.
cURL
curl -X POST https://screenshot-api.net/your-endpoint
-H 'Authorization: Bearer PROVIDER_TOKEN'
-H 'Content-Type: application/json'
--data '{"url":"https://portal.example.com/report","headers":{"X-Preview-Token":"PAGE_TOKEN"}}'
Python
import os
import requests
r = requests.post(
"https://screenshot-api.net/your-endpoint",
headers={"Authorization": f"Bearer {os.environ['PROVIDER_TOKEN']}"},
json={
"url": "https://portal.example.com/report",
"headers": {"X-Preview-Token": os.environ["PAGE_TOKEN"]},
},
timeout=90,
)
r.raise_for_status()
print(r.json())
Node.js
const providerToken = process.env.PROVIDER_TOKEN;
const pageToken = process.env.PAGE_TOKEN;
const res = await fetch('https://screenshot-api.net/your-endpoint', {
method: 'POST',
headers: {
Authorization: `Bearer ${providerToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
url: 'https://portal.example.com/report',
headers: { 'X-Preview-Token': pageToken }
})
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server. It accepts a URL in one GET request and can return PNG, JPEG, WebP or PDF. For a Java application, call it with the standard HTTP client and pass target-page headers using ScreenshotNeo’s documented options at https://screenshotneo.com/docs/.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
ScreenshotNeo removes cookie-consent banners, newsletter popups and chat widgets before capture. Bot checks, blank pages, timeouts, failed loads and cache hits are not billed, and each response identifies the page verdict and billing result with X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Sign up for the free plan.
Operational and cost considerations
- Set a realistic Java connect and overall request timeout; a slow authenticated page can need more time than a static page.
- Reuse one configured
HttpClientso connections can be pooled. - Redact authorization headers, cookies and target tokens from logs and exception telemetry.
- Keep target credentials short-lived and scoped to the smallest permitted resource.
- Measure final-page status, render duration and cache behavior separately from Java transport latency.
- Check provider billing rules: a successful API HTTP response does not necessarily mean the page was successfully rendered.
Frequently Asked Questions
Can I add a target-site header with only Java’s HttpClient?
No. Java can add headers to the request it sends, but a hosted screenshot browser needs a provider-supported target-page header option to receive a header during navigation.
Best Value
Should I use a header or a cookie for authentication?
Use the mechanism the target application accepts. Token-header authentication can use a target header; session-based applications generally require the provider’s cookie support.
Is it safe to enable restricted Java headers in production?
The JDK documents the override as intended for testing and warns about protocol errors or undefined behavior. Avoid it in normal production code.
Quick Recap
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.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →




