### Unirest Configuration Example Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/upgrade-guide.md Demonstrates how to configure Unirest settings like timeouts, proxy, default headers, redirects, cookie management, and interceptors using the centralized Unirest.config() method. ```java Unirest.config() .connectTimeout(1000) .proxy(new Proxy("https://proxy")) .setDefaultHeader("Accept", "application/json") .followRedirects(false) .enableCookieManagement(false) .addInterceptor(new MyCustomInterceptor()); ``` -------------------------------- ### Query Parameters Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/requests.md Demonstrates how to add multiple query parameters to a GET request, including using arrays and maps. ```APIDOC ## GET / ### Description Sends a GET request to the root path with multiple query parameters. Parameters can be added individually, as an array of values for a single key, or from a map. ### Method GET ### Endpoint http://localhost ### Parameters #### Query Parameters - **fruit** (string or array of strings) - Required - The fruit(s) to query. - **droid** (string) - Required - The droid identifier. - **beatle** (string) - Required - The Beatle identifier. ### Request Example ```java // Individual parameters Unirest.get("http://localhost") .queryString("fruit", "apple") .queryString("droid", "R2D2") .asString(); // Array and Map parameters Unirest.get("http://localhost") .queryString("fruit", Arrays.asList("apple", "orange")) .queryString(ImmutableMap.of("droid", "R2D2", "beatle", "Ringo")) .asString(); ``` ### Response #### Success Response (200) - **body** (string) - The response body as a string. #### Response Example (Response content depends on the server) ``` -------------------------------- ### Accessing and Configuring Primary Unirest Instance Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/upgrade-guide.md Demonstrates how to get the primary Unirest instance, which is the same instance used by static Unirest calls. It can be configured and used independently. ```java UnirestInstance unirest = Unirest.primaryInstance(); unirest.config().connectTimeout(5000); String result = unirest.get("http://foo").asString().getBody(); ``` -------------------------------- ### Implement Custom Cache with Guava Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/caching.md Supply a custom cache implementation by extending the Cache interface. This example demonstrates using Guava's CacheBuilder for managing cache entries. ```java public static void main(String[] args){ Unirest.config().cacheResponses(Cache.builder().backingCache(new GuavaCache())); } // Example backing cache using Guava public static class GuavaCache implements Cache { com.google.common.cache.Cache regular = CacheBuilder.newBuilder().build(); com.google.common.cache.Cache async = CacheBuilder.newBuilder().build(); @Override public HttpResponse get(Key key, Supplier> fetcher) { try { return regular.get(key, fetcher::get); } catch (ExecutionException e) { throw new RuntimeException(e); } } @Override public CompletableFuture getAsync(Key key, Supplier>> fetcher) { try { return async.get(key, fetcher::get); } catch (ExecutionException e) { throw new RuntimeException(e); } } } ``` -------------------------------- ### Install Unirest 3 with Maven Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/installation.md Add this traditional Maven dependency to include Unirest 3 in your project. This is for users who are not yet on Unirest 4. ```xml com.konghq unirest-java 3.14.1 ``` -------------------------------- ### Get and Configure Primary Unirest Instance Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/configuration.md Retrieve the primary Unirest instance to configure its connection timeout and use it for making requests. ```java // this returns the same instance used by Unirest.get("http://somewhere/") UnirestInstance unirest = Unirest.primaryInstance(); // It can be configured and used just like the static context unirest.config().connectTimeout(5000); String result = unirest.get("http://foo").asString().getBody(); ``` -------------------------------- ### Get Response as String Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/responses.md Retrieve the response body directly as a String using `asString()`. This is useful for simple text-based responses. ```java String body = Unirest.get("http://localhost") .asString() .getBody(); ``` -------------------------------- ### Install Unirest 4 with Maven BOM Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/installation.md Use this Maven configuration to manage Unirest 4 dependencies with a Bill of Materials (BOM). This approach helps in managing module versions and avoiding conflicts. ```xml com.konghq unirest-java-bom 4.5.1 pom import com.konghq unirest-java-core com.konghq unirest-modules-gson com.konghq unirest-modules-jackson ``` -------------------------------- ### Install Unirest Gson Object Mapper with Maven Source: https://github.com/kong/unirest-java/blob/main/unirest-modules-gson/README.md Add the unirest-object-mappers-gson dependency to your Maven project to enable Gson integration. ```xml com.konghq unirest-object-mappers-gson 2.0.00 ``` -------------------------------- ### Mocking Responses with Status, Headers, and Body Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/mocks.md Configure MockClient to return a specific status code, headers, and a string body for a GET request. This is useful for testing how your application handles various server responses. ```java @Test void response() { MockClient mock = MockClient.register(); mock.expect(HttpMethod.GET, "http://zombo.com") .thenReturn("Care for some tea mum?") .withHeader("x-zombo-brewing", "active") .withStatus(418, "I am a teapot"); var response = Unirest.get("http://zombo.com").asString(); assertEquals(418, response.getStatus()); assertEquals("I am a teapot", response.getStatusText()); assertEquals("Care for some tea mum?", response.getBody()); assertEquals("active", response.getHeaders().getFirst("x-zombo-brewing")); } ``` -------------------------------- ### Install Unirest Jackson ObjectMapper with Maven Source: https://github.com/kong/unirest-java/blob/main/unirest-modules-jackson/README.md Add the unirest-objectmapper-jackson dependency to your Maven project to include the Jackson object mapper. ```xml com.konghq unirest-objectmapper-jackson 3.0.01 ``` -------------------------------- ### Fetch Paged Data with Unirest Java Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/requests.md Handle paginated API responses by providing functions to parse the response and extract the next page link. This example assumes the 'next' link is in the headers. ```java PagedList result = Unirest.get("https://somewhere/dogs") .asPaged( r -> r.asObject(Doggos.class), r -> r.getHeaders().getFirst("nextPage") ); ``` -------------------------------- ### Configure Client Certificate from File Path Source: https://context7.com/kong/unirest-java/llms.txt Sets the client certificate store using a file path to a PKCS#12 keystore. The keystore password is also provided. ```java Unirest.config().clientCertificateStore("/etc/certs/client.p12", "keystorePassword"); ``` -------------------------------- ### Previous Unirest Configuration Methods Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/upgrade-guide.md Illustrates the older, fragmented ways of configuring Unirest, showing settings applied either directly on Unirest or on the Options class. ```java // Sometimes it was on Unirest Unirest.setTimeouts(5000, 10000); //Sometimes it was on Options Options.setOption(HTTPCLIENT, client); ``` -------------------------------- ### Download Files with Progress Monitoring in Java Source: https://context7.com/kong/unirest-java/llms.txt Use the `asFile()` method to save response bodies to disk and provide a `downLoadMonitor` callback to track download progress. ```java File downloaded = Unirest.get("https://example.com/reports/monthly.pdf") .header("Authorization", "Bearer " + token) .downLoadMonitor((field, fileName, bytesWritten, totalBytes) -> { if (totalBytes > 0) { int pct = (int) (bytesWritten * 100 / totalBytes); System.out.printf("\rDownloading %s: %d%%", fileName, pct); } }) .asFile("/tmp/monthly.pdf") .getBody(); System.out.println("\nSaved to: " + downloaded.getAbsolutePath()); ``` -------------------------------- ### Configure Client Certificate from KeyStore Object Source: https://context7.com/kong/unirest-java/llms.txt Loads a client certificate from a `KeyStore` object, which must be pre-initialized and populated with the certificate. The keystore password is required. ```java KeyStore ks = KeyStore.getInstance("PKCS12"); try (var is = new FileInputStream("/etc/certs/client.p12")) { ks.load(is, "keystorePassword".toCharArray()); } Unirest.config().clientCertificateStore(ks, "keystorePassword"); ``` -------------------------------- ### Get JSON Object from Response Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/responses.md Access nested JSON objects and arrays from a response body. Ensure the response content type is JSON. ```java String result = Unirest.get("http://some.json.com") .asJson() .getBody() .getObject() .getJSONObject("car") .getJSONArray("wheels") .get(0) ``` -------------------------------- ### Configure Simple Proxy with Authentication Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/proxies.md Set a single proxy with authentication details. This configures a basic ProxySelector and Authenticator. ```java Unirest.config().proxy("proxy.com", 7777, "username", "password1!"); ``` -------------------------------- ### Configure Proxies Using System Settings Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/proxies.md Utilize Java's system properties for proxy configuration. Ensure system properties like http.proxyHost and http.proxyPort are set before calling useSystemProperties(true). ```java System.setProperty("http.proxyHost", "localhost"); System.setProperty("http.proxyPort", "7777"); Unirest.config().useSystemProperties(true); ``` -------------------------------- ### Configure Simple Authenticated Proxy Source: https://context7.com/kong/unirest-java/llms.txt Sets up a simple HTTP proxy with authentication credentials. This configuration applies globally to all Unirest requests. ```java Unirest.config().proxy("corp-proxy.example.com", 8080, "proxyUser", "proxyPass"); ``` -------------------------------- ### Configure Global Unirest Settings Source: https://context7.com/kong/unirest-java/llms.txt Centralize Unirest settings like base URL, timeouts, default headers, and authentication using `Unirest.config()`. Apply these once at startup. A `reset()` is needed to modify client-affecting options after activation. ```java Unirest.config() .defaultBaseUrl("https://api.example.com") // base for relative URLs .connectTimeout(5_000) // ms .requestTimeout(30_000) // ms (0 = infinite) .setDefaultHeader("Accept", "application/json") .setDefaultHeader("x-api-key", () -> vaultClient.getSecret("api-key")) // supplier for dynamic values .setDefaultBasicAuth("serviceUser", "servicePass") .followRedirects(true) .verifySsl(true) .enableCookieManagement(true) .retryAfter(true, 3) // auto-retry on 429/529 up to 3 times .cacheResponses(Cache.builder() .depth(100) .maxAge(5, TimeUnit.MINUTES)); ``` -------------------------------- ### Resetting and Reconfiguring Unirest Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/upgrade-guide.md Shows how to reset Unirest's configuration to default values and then apply new settings. This is useful when needing to change client creation parameters after initial activation. ```java Unirest.config() .reset() .connectTimeout(5000) ``` -------------------------------- ### Basic Authentication Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/requests.md Shows how to implement basic HTTP authentication using Unirest, which handles Base64 encoding. ```APIDOC ## GET / ### Description Sends a GET request with Basic Authentication credentials. Unirest automatically encodes the username and password and adds the `Authorization` header. ### Method GET ### Endpoint http://localhost ### Parameters #### Headers - **Authorization** (string) - Automatically generated with Basic Auth credentials. ### Request Example ```java Unirest.get("http://localhost") .basicAuth("user", "password1!") .asString(); ``` ### Response #### Success Response (200) - **body** (string) - The response body as a string. #### Response Example (Response content depends on the server) ``` -------------------------------- ### Configure Client Certificate Store with Unirest Java Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/requests.md Set a custom client certificate keystore for secure connections by providing the path to a PKCS#12 file and its password. ```java Unirest.config() .clientCertificateStore("/path/mykeystore.p12", "password1!"); Unirest.get("https://some.custom.secured.place.com") .asString(); ``` -------------------------------- ### Spawning a New Unirest Instance Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/upgrade-guide.md Shows how to create a completely new, independent Unirest instance. Remember that you are responsible for shutting down these spawned instances manually. ```java UnirestInstance unirest = Unirest.spawnInstance(); ``` -------------------------------- ### Basic POST Request Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/requests.md Demonstrates a basic POST request with headers, query parameters, and form fields, and how to specify the response type. ```APIDOC ## POST /post ### Description Sends a POST request to the specified URL with custom headers, query parameters, and form fields. The response can be processed as JSON. ### Method POST ### Endpoint http://localhost/post ### Parameters #### Query Parameters - **apiKey** (string) - Required - The API key for authentication. #### Request Body - **parameter** (string) - Required - A sample parameter. - **firstname** (string) - Required - The first name. #### Headers - **accept** (string) - Required - Specifies the expected response content type, e.g., `application/json`. ### Request Example ```java HttpResponse response = Unirest.post("http://localhost/post") .header("accept", "application/json") .queryString("apiKey", "123") .field("parameter", "value") .field("firstname", "Gary") .asJson(); ``` ### Response #### Success Response (200) - **body** (JsonNode) - The JSON response body. #### Response Example (Response structure depends on the server's implementation) ``` -------------------------------- ### Configure Proxy Using System Properties Source: https://context7.com/kong/unirest-java/llms.txt Enables Unirest to use JVM system properties for proxy configuration (e.g., http.proxyHost, https.proxyPort). Ensure system properties are set before calling this. ```java System.setProperty("https.proxyHost", "proxy.internal.com"); System.setProperty("https.proxyPort", "3128"); Unirest.config().useSystemProperties(true); ``` -------------------------------- ### Route Parameters Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/requests.md Shows how to use route parameters to dynamically insert values into the URL path. ```APIDOC ## GET /{fruit} ### Description Sends a GET request to a URL with a dynamic route parameter. The parameter is specified using curly braces in the URL and then provided via the `routeParam` method. ### Method GET ### Endpoint http://localhost/{fruit} ### Parameters #### Path Parameters - **fruit** (string) - Required - The name of the fruit to be included in the URL. ### Request Example ```java Unirest.get("http://localhost/{fruit}") .routeParam("fruit", "apple") .asString(); ``` ### Response #### Success Response (200) - **body** (string) - The response body as a string. #### Response Example (Response content depends on the server) ``` -------------------------------- ### Configure Per-Host Proxy Selector Source: https://context7.com/kong/unirest-java/llms.txt Implements a custom `ProxySelector` to dynamically determine proxy settings based on the request URI. This allows for granular proxy configuration per host. ```java Unirest.config().proxy(new ProxySelector() { @Override public List select(URI uri) { if (uri.getHost().endsWith("partner.com")) { return List.of(new java.net.Proxy( java.net.Proxy.Type.HTTP, InetSocketAddress.createUnresolved("partner-proxy.com", 8080))); } return List.of(java.net.Proxy.NO_PROXY); } @Override public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { /* log */ } }); ``` -------------------------------- ### Instrument Unirest with Basic Metrics Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/configuration.md Configure Unirest to instrument requests with basic metrics, logging the request path, status, and execution time. ```java Unirest.config().instrumentWith(requestSummary -> { long startNanos = System.nanoTime(); return (responseSummary,exception) -> logger.info("path: {} status: {} time: {}", requestSummary.getRawPath(), responseSummary.getStatus(), System.nanoTime() - startNanos); }); ``` -------------------------------- ### Monitor Download Progress Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/responses.md Implement `DownloadMonitor` to track the progress of file downloads, providing feedback to the user, especially for large files. ```java Unirest.get("http://localhost") .downLoadMonitor((b, fileName, bytesWritten, totalBytes) -> { updateProgressBarWithBytesLeft(totalBytes - bytesWritten); }) .asFile("/disk/location/file.zip"); ``` -------------------------------- ### Post an InputStream as a File with Unirest Java Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/requests.md For large files, use an InputStream and provide a filename. Any InputStream can be used. ```java InputStream file = new FileInputStream(new File("/MyFile.zip")); Unirest.post("http://localhost") .field("upload", file, "MyFile.zip") .asEmpty(); ``` -------------------------------- ### Download Response Body to File Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/responses.md Save the response body directly to a specified file path using `asFile()`. This is ideal for downloading files. ```java File result = Unirest.get("http://some.file.location/file.zip") .asFile("/disk/location/file.zip") .getBody(); ``` -------------------------------- ### Basic Authentication Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/requests.md Implement basic HTTP authentication using the `basicAuth` method. Unirest handles the Base64 encoding. It is recommended to use this over HTTPS. ```java Unirest.get("http://localhost") .basicAuth("user", "password1!") .asString(); // this adds the header "Authorization: Basic dXNlcjpwYXNzd29yZDEh" ``` -------------------------------- ### Configure Multiple Proxies with Custom ProxySelector and Authenticator Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/proxies.md Handle multiple proxies by implementing a custom ProxySelector and Authenticator. This allows different proxy configurations based on the URI, and provides authentication credentials when required. ```java Unirest.config() .proxy(new ProxySelector() { @Override public List select(URI uri) { if (uri.getHost().equals("homestarrunner.com")) { return List.of(new java.net.Proxy(HTTP, InetSocketAddress.createUnresolved("proxy-sad.com", 7777))); } return List.of(new java.net.Proxy(HTTP, InetSocketAddress.createUnresolved("default.com", 7777))); } @Override public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { } }) .authenticator(new Authenticator() { @Override public PasswordAuthentication requestPasswordAuthenticationInstance(String host, InetAddress addr, int port, String protocol, String prompt, String scheme, URL url, RequestorType reqType) { // Please don't hardcode passwords in your code :D if(host.equals("homestarrunner.com")) { return new PasswordAuthentication("strongbad", "password".toCharArray()); } return new PasswordAuthentication("default", "password".toCharArray()); } }); ``` -------------------------------- ### Setting Custom Apache Clients Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/upgrade-guide.md Illustrates how to provide custom Apache HttpClient and HttpAsyncClient instances to Unirest. Note that Unirest's own settings like timeouts will not be applied to these custom clients. ```java Unirest.config() .httpClient(myClient) .asyncClient(myAsyncClient) ``` -------------------------------- ### Configure Proxy using Unirest Proxy Object Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/proxies.md Set a single proxy by passing a Unirest Proxy object. ```java Unirest.config().proxy(new Proxy("proxy.com", 7777)); ``` -------------------------------- ### Map Response to Specific Object with Route Parameters Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/responses.md Fetch and map a specific resource to an object using route parameters for dynamic URL construction. ```java Author author = Unirest.get("http://localhost/books/{id}/author") .routeParam("id", bookObject.getId()) .asObject(Author.class) .getBody(); ``` -------------------------------- ### Headers Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/requests.md Illustrates how to add custom headers to an HTTP request. ```APIDOC ## GET / ### Description Sends a GET request with custom headers. Headers can be added individually using the `header` method. ### Method GET ### Endpoint http://localhost ### Parameters #### Headers - **Accept** (string) - Required - Specifies the expected response content type. - **x-custom-header** (string) - Required - A custom header. ### Request Example ```java Unirest.get("http://localhost") .header("Accept", "application/json") .header("x-custom-header", "hello") .asString(); ``` ### Response #### Success Response (200) - **body** (string) - The response body as a string. #### Response Example (Response content depends on the server) ``` -------------------------------- ### Download Progress Monitoring Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/responses.md Monitor the progress of file downloads by providing a `DownloadMonitor` callback. ```APIDOC ### Download Progress Monitoring If you are uploading large files you might want to provide some time of progress bar to a user. You can monitor this progress by providing a ProgresMonitor. ```java Unirest.get("http://localhost") .downLoadMonitor((b, fileName, bytesWritten, totalBytes) -> { updateProgressBarWithBytesLeft(totalBytes - bytesWritten); }) .asFile("/disk/location/file.zip"); ``` ``` -------------------------------- ### Make Request with Client Certificate Source: https://context7.com/kong/unirest-java/llms.txt After configuring the client certificate store, subsequent Unirest requests will automatically present the client certificate for mutual TLS authentication. ```java // Requests now automatically present the client certificate HttpResponse resp = Unirest.get("https://mtls-api.example.com/data").asString(); ``` -------------------------------- ### Register Static Mock Client Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/mocks.md Register a mock client with Unirest's static implementation to intercept requests. Use this for testing the default Unirest interface. ```java class MyTest { @Test void mockStatic(){ MockClient mock = MockClient.register(); mock.expect(HttpMethod.GET, "http://zombo.com") .thenReturn("You can do anything!"); assertEquals( "You can do anything!", Unirest.get("http://zombo.com").asString().getBody() ); } } ``` -------------------------------- ### Route Parameters and Query Strings in Unirest Java Source: https://context7.com/kong/unirest-java/llms.txt Use {placeholder} syntax for route parameters, substituted with routeParam(). Query parameters are added with queryString() and automatically URL-encoded. Both support single values, arrays, and maps. ```java // Route parameter substitution HttpResponse res = Unirest.get("https://api.example.com/users/{id}/posts/{postId}") .routeParam("id", "42") .routeParam("postId", "7") .asString(); // → GET https://api.example.com/users/42/posts/7 // Multiple query parameters (array + map) Unirest.get("https://api.example.com/search") .queryString("tag", Arrays.asList("java", "http")) .queryString(Map.of("page", "1", "size", "20")) .asString(); // → GET https://api.example.com/search?tag=java&tag=http&page=1&size=20 ``` -------------------------------- ### Configure Custom Cache with Guava Source: https://context7.com/kong/unirest-java/llms.txt Integrates a custom cache implementation backed by Guava, allowing for more advanced caching strategies like maximum size and expiration. ```java Unirest.config().cacheResponses(Cache.builder().backingCache(new Cache() { com.google.common.cache.Cache store = CacheBuilder.newBuilder().maximumSize(500).expireAfterWrite(5, TimeUnit.MINUTES).build(); @Override public HttpResponse get(Cache.Key key, Supplier> fetcher) { try { return store.get(key, fetcher::get); } catch (ExecutionException e) { throw new RuntimeException(e); } } @Override public CompletableFuture getAsync(Cache.Key key, Supplier>> fetcher) { return fetcher.get(); // delegate async, or implement similarly } })); ``` -------------------------------- ### Spawn a New Unirest Instance Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/configuration.md Create a completely new, independent Unirest instance that can be configured separately from the primary instance. ```java // You can also get a whole new instance UnirestInstance unirest = Unirest.spawnInstance(); ``` -------------------------------- ### File Responses Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/responses.md Handle responses as files, either by specifying a download location or capturing the body into a file. ```APIDOC ## File Responses Sometimes you just want to download a file, or maybe capture the response body into a file. Unirest can do both. Just tell Unirest where you want to put the file. ```java File result = Unirest.get("http://some.file.location/file.zip") .asFile("/disk/location/file.zip") .getBody(); ``` ``` -------------------------------- ### Create Independent Unirest Instances Source: https://context7.com/kong/unirest-java/llms.txt Use `Unirest.spawnInstance()` to create separate `UnirestInstance` objects with distinct configurations for different services. Remember to shut down spawned instances when no longer needed. ```java // Primary instance (shared static) UnirestInstance primary = Unirest.primaryInstance(); primary.config().defaultBaseUrl("https://api.internal.com"); // Isolated instance for an external service UnirestInstance external = Unirest.spawnInstance(); external.config() .defaultBaseUrl("https://partner.api.com") .connectTimeout(2_000) .setDefaultHeader("x-partner-token", "tok_live_abc123"); String internalData = primary.get("/data").asString().getBody(); String partnerData = external.get("/partner/data").asString().getBody(); // Important: you are responsible for shutting down spawned instances external.shutDown(); ``` -------------------------------- ### Register Instance Mock Client Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/mocks.md Register a mock client with a specific Unirest instance to intercept requests made by that instance. This is useful when you need to isolate mocks for different parts of your application. ```java @Test void mockInstant(){ UnirestInstance unirest = Unirest.spawnInstance(); MockClient mock = MockClient.register(unirest); mock.expect(HttpMethod.GET, "http://zombo.com") .thenReturn("You can do anything!"); assertEquals( "You can do anything!", unirest.get("http://zombo.com").asString().getBody() ); } ``` -------------------------------- ### Asynchronous Requests Source: https://context7.com/kong/unirest-java/llms.txt Details how to perform asynchronous HTTP requests using Unirest. It covers using callbacks and composing `CompletableFuture` objects for handling responses. ```APIDOC ## Asynchronous Requests All terminal methods have async counterparts (e.g., `asStringAsync()`, `asJsonAsync()`, `asObjectAsync()`). They accept an optional callback and always return `CompletableFuture>`. ```java // Fire-and-forget with callback CompletableFuture> future = Unirest.post("https://api.example.com/events") .header("accept", "application/json") .field("type", "click") .field("target", "button#submit") .asJsonAsync(response -> { if (response.isSuccess()) { System.out.println("Recorded: " + response.getBody()); } else { System.err.println("Failed: " + response.getStatus()); } }); // Compose with other futures future.thenApply(HttpResponse::getBody) .thenAccept(json -> System.out.println("Event ID: " + json.getObject().get("id"))); ``` ``` -------------------------------- ### Upload Files with Unirest Source: https://context7.com/kong/unirest-java/llms.txt Use the `.field()` method for form fields and files. Implement `uploadMonitor` for progress feedback during file uploads. ```java // File upload (multipart/form-data) Unirest.post("https://api.example.com/upload") .field("description", "my archive") .field("file", new File("/path/to/archive.zip")) .uploadMonitor((field, fileName, bytesWritten, totalBytes) -> System.out.printf("Uploaded %d / %d bytes%n", bytesWritten, totalBytes)) .asEmpty(); ``` -------------------------------- ### Route Parameters Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/requests.md Dynamically add parameters to a URL by using placeholders enclosed in curly braces `{}` and setting them with the `routeParam` function. All parameter values are URL-encoded. ```java Unirest.get("http://localhost/{fruit}") .routeParam("fruit", "apple") .asString(); // Results in `http://localhost/apple` ``` -------------------------------- ### Default Base URLs Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/requests.md Explains how to configure a default base URL to simplify requests that share a common base. ```APIDOC ## GET /runner ### Description Configures a default base URL for subsequent requests. When a request is made without a full URL, the default base URL is prepended. ### Method GET ### Endpoint http://homestar.com/runner ### Request Example ```java Unirest.config().defaultBaseUrl("http://homestar.com"); Unirest.get("/runner").asString(); ``` ### Response #### Success Response (200) - **body** (string) - The response body as a string. #### Response Example (Response content depends on the server) ``` -------------------------------- ### Configure Simple Proxy without Authentication Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/proxies.md Set a single proxy without authentication. This configures a basic ProxySelector. ```java Unirest.config().proxy("proxy.com", 7777); ``` -------------------------------- ### Basic HTTP Requests with Unirest Java Source: https://context7.com/kong/unirest-java/llms.txt Unirest provides static methods for HTTP verbs. Execute requests using terminal methods like asString(), asJson(), asObject(), asFile(), asBytes(), and asEmpty(). ```java import kong.unirest.core.*; // GET → String String body = Unirest.get("https://httpbin.org/get") .header("Accept", "application/json") .asString() .getBody(); // POST with form fields → JSON response HttpResponse response = Unirest.post("https://httpbin.org/post") .header("accept", "application/json") .field("username", "alice") .field("role", "admin") .asJson(); System.out.println(response.getStatus()); // 200 System.out.println(response.getBody().toString()); // {"form":{"username":"alice","role":"admin"}, ...} // DELETE → ignore body HttpResponse del = Unirest.delete("https://httpbin.org/delete").asEmpty(); System.out.println(del.getStatus()); // 200 ``` -------------------------------- ### Multiple Request Expectations Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/mocks.md Set up multiple expectations for Unirest requests. The most specific matching expectation, determined by a point system, will be used for a given request. ```java @Test void multipleExpects(){ MockClient mock = MockClient.register(); mock.expect(HttpMethod.POST, "https://somewhere.bad") .thenReturn("I'm Bad"); mock.expect(HttpMethod.GET, "http://zombo.com") .thenReturn("You can do anything!"); mock.expect(HttpMethod.GET, "http://zombo.com") .header("foo", "bar") .thenReturn("You can do anything with headers!"); assertEquals( "You can do anything with headers!", Unirest.get("http://zombo.com") .header("foo", "bar") .asString().getBody() ); assertEquals( "You can do anything!", Unirest.get("http://zombo.com") .asString().getBody() ); } ``` -------------------------------- ### Instrument Requests for Metrics Source: https://context7.com/kong/unirest-java/llms.txt Use `instrumentWith()` for lightweight before/after hooks to time requests and collect metrics without a full `Interceptor`. This provides callbacks for request completion or exceptions. ```java Unirest.config().instrumentWith(requestSummary -> { long start = System.nanoTime(); String path = requestSummary.getRawPath(); return (responseSummary, exception) -> { long elapsedMs = (System.nanoTime() - start) / 1_000_000; if (exception != null) { metrics.increment("http.error", "path", path); } else { metrics.record("http.latency", elapsedMs, "path", path, "status", String.valueOf(responseSummary.getStatus())); } }; }); ``` -------------------------------- ### Execute Asynchronous Requests with Unirest Source: https://context7.com/kong/unirest-java/llms.txt Use async counterparts like `asJsonAsync()` which return a `CompletableFuture>`. An optional callback can be provided for immediate handling of the response. ```java // Fire-and-forget with callback CompletableFuture> future = Unirest.post("https://api.example.com/events") .header("accept", "application/json") .field("type", "click") .field("target", "button#submit") .asJsonAsync(response -> { if (response.isSuccess()) { System.out.println("Recorded: " + response.getBody()); } else { System.err.println("Failed: " + response.getStatus()); } }); // Compose with other futures future.thenApply(HttpResponse::getBody) .thenAccept(json -> System.out.println("Event ID: " + json.getObject().get("id"))); ``` -------------------------------- ### Enable Basic In-Memory Caching Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/caching.md Enable the default in-memory caching mechanism. Subsequent identical requests will serve cached responses. ```java Unirest.config().cacheResponses(true); //These 1st response will be cached in this case: Unirest.get("https://somwhere").asString(); Unirest.get("https://somwhere").asString(); ``` -------------------------------- ### Default Base URL Configuration Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/requests.md Configure a default base URL to be used for all requests that do not specify a full URL. This simplifies requests by allowing you to omit the base part of the URL. ```java Unirest.config().defaultBaseUrl("http://homestar.com"); Unirest.get("/runner").asString(); ``` -------------------------------- ### Post a File with Unirest Java Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/requests.md Use the .field() method to upload a file. The Content-Type defaults to multipart/form-data. ```java Unirest.post("http://localhost") .field("upload", new File("/MyFile.zip")) .asEmpty(); ``` -------------------------------- ### Basic POST Request Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/requests.md A basic POST request with headers, query parameters, and form fields. Requests are finalized by invoking an `as[Type]()` method, with supported types including Json, String, Object, Empty, and File. ```java HttpResponse response = Unirest.post("http://localhost/post") .header("accept", "application/json") .queryString("apiKey", "123") .field("parameter", "value") .field("firstname", "Gary") .asJson(); ``` -------------------------------- ### Maven Dependencies for Unirest Java Source: https://context7.com/kong/unirest-java/llms.txt Add the Unirest BOM to dependencyManagement and then declare the necessary modules. Choose one or both JSON modules and optionally include mock support for testing. ```xml com.konghq unirest-java-bom 4.5.1 pom import com.konghq unirest-java-core com.konghq unirest-modules-gson com.konghq unirest-modules-jackson com.konghq unirest-modules-mocks test ``` -------------------------------- ### Handle Empty Responses Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/responses.md Use `asEmpty()` when no response body is expected or needed. This method still provides access to status and headers. ```java HttpResponse response = Unirest.delete("http://localhost").asEmpty(); ``` -------------------------------- ### Configure In-Memory Response Caching Source: https://context7.com/kong/unirest-java/llms.txt Enables simple in-memory caching with a specified depth and maximum age for entries. Ensure Unirest is configured before making requests. ```java Unirest.config().cacheResponses(Cache.builder() .depth(200) // max number of cached entries .maxAge(10, TimeUnit.MINUTES)); // TTL per entry ``` -------------------------------- ### String Responses Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/responses.md Retrieve the response body as a String using `asString`. ```APIDOC ## String Responses The next easiest response type is String. You can do whatever you want with it after that. ```java String body = Unirest.get("http://localhost") .asString() .getBody(); ``` ``` -------------------------------- ### Configure Advanced Cache Options Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/caching.md Customize cache behavior using a builder to set the maximum number of cached entries (depth) and the maximum age of entries before they expire. ```java Unirest.config().cacheResponses(builder() .depth(5) // Depth is the max number of entries cached .maxAge(5, TimeUnit.MINUTES)); // Max age is how long the entry will be kept. ``` -------------------------------- ### Mocking Form Parameters Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/mocks.md Use MockClient to define expected form parameters for a POST request. This ensures that the request sent by Unirest matches the expected fields and values. ```java @Test void formParams() { MockClient mock = MockClient.register(); mock.expect(HttpMethod.POST, "http://zombo.com") .body(FieldMatcher.of("foo", "bar", "baz", "qux")) .thenReturn() .withStatus(201); assertEquals(201, Unirest.post("http://zombo.com") .field("foo", "bar") .field("baz", "qux") .asEmpty().getStatus() ); } ``` -------------------------------- ### Query Parameters Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/requests.md Add query-string parameters one by one using the `queryString` method. All parameter values are URL-encoded. Supports adding multiple values for the same parameter key using lists or maps. ```java Unirest.get("http://localhost") .queryString("fruit", "apple") .queryString("droid", "R2D2") .asString(); // Results in "http://localhost?fruit=apple&droid=R2D2" ``` ```java Unirest.get("http://localhost") .queryString("fruit", Arrays.asList("apple", "orange")) .queryString(ImmutableMap.of("droid", "R2D2", "beatle", "Ringo")) .asString(); // Results in "http://localhost?fruit=apple&fruit=orange&droid=R2D2&beatle=Ringo" ``` -------------------------------- ### Monitor File Upload Progress with Unirest Java Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/requests.md Provide an uploadMonitor callback to track the progress of file uploads, useful for large files. ```java Unirest.post("http://localhost") .field("upload", new File("/MyFile.zip")) .uploadMonitor((field, fileName, bytesWritten, totalBytes) -> { updateProgressBarWithBytesLeft(totalBytes - bytesWritten); }) .asEmpty(); ``` -------------------------------- ### Basic Forms Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/requests.md Explains how to send basic HTTP form data using the `field` method, which defaults to `application/x-www-form-urlencoded` content type. ```APIDOC ## POST / ### Description Sends a POST request with basic form data. Key-value pairs are added using the `field` method, and the `Content-Type` is set to `application/x-www-form-urlencoded` by default. ### Method POST ### Endpoint http://localhost ### Parameters #### Request Body - **fruit** (string) - Required - The name of the fruit. - **droid** (string) - Required - The identifier for the droid. ### Request Example ```java Unirest.post("http://localhost") .field("fruit", "apple") .field("droid", "R2D2") .asEmpty(); ``` ### Response #### Success Response (200) (Response type depends on `asEmpty()` or other `as` methods used) #### Response Example (Response content depends on the server) ``` -------------------------------- ### Paged Requests Source: https://context7.com/kong/unirest-java/llms.txt Illustrates how to handle paginated APIs using `asPaged()`. This method automatically follows pagination links based on provided functions for executing requests and extracting the next page URL. ```APIDOC ## Paged Requests `asPaged()` automatically follows paginated APIs. It takes two functions: one to execute the request and one to extract the URL of the next page from each response. The result is a `PagedList>`. ```java // Follow pagination where the next-page URL is in a "nextPage" response header PagedList>> pages = Unirest.get("https://api.example.com/articles") .queryString("pageSize", "50") .asPaged( r -> r.asObject(new GenericType>() {}), r -> r.getHeaders().getFirst("nextPage") // returns null/empty to stop ); pages.forEach(page -> page.getBody().forEach(article -> System.out.println(article.getTitle()))); // Check for any failures across pages pages.ifFailure(err -> System.err.println("A page failed: " + err.getStatus())); ``` ``` -------------------------------- ### Consume Server-Sent Events Asynchronously Source: https://context7.com/kong/unirest-java/llms.txt Establishes a persistent SSE connection and processes incoming events asynchronously using a callback. The `CompletableFuture` returned can be used to manage the stream's lifecycle. ```java CompletableFuture stream = Unirest.sse("https://stream.wikimedia.org/v2/stream/recentchange") .connect(event -> { RecentChange change = event.asObject(RecentChange.class); System.out.println("Page changed: " + change.getTitle()); }); // Wait for the stream to finish (it usually won't unless the server closes it) stream.join(); ``` -------------------------------- ### Perform Asynchronous POST Request with Unirest Java Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/requests.md Execute requests asynchronously using CompletableFuture and callbacks to handle responses without blocking the main thread. ```java CompletableFuture> future = Unirest.post("http://localhost/post") .header("accept", "application/json") .field("param1", "value1") .field("param2", "value2") .asJsonAsync(response -> { int code = response.getStatus(); JsonNode body = response.getBody(); }); ``` -------------------------------- ### Add Jackson Object Mapper Dependency Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/configuration.md Include the Jackson module dependency to enable Jackson-based object mapping in Unirest. ```xml com.konghq unirest-modules-jackson ``` -------------------------------- ### Map Response to Object Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/responses.md Use `asObject(Class)` to map JSON responses directly into Java objects. Ensure an `ObjectMapper` is configured globally. ```java Book book = Unirest.get("http://localhost/books/1") .asObject(Book.class) .getBody(); ``` -------------------------------- ### Empty Responses Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/responses.md Use `asEmpty` when you don't expect or care about a response body. It still provides access to status and headers. ```APIDOC ## Empty Responses If you aren't expecting a body back, or you don't care about the body, `asEmpty` is the easiest choice. You will still get back response information like status and headers. Note that this method effectively ignores any body that might be present. ```java HttpResponse response = Unirest.delete("http://localhost").asEmpty(); ``` ``` -------------------------------- ### Request Headers and Basic Authentication in Unirest Java Source: https://context7.com/kong/unirest-java/llms.txt Add custom headers using header(). The basicAuth() method is a shortcut for Base64-encoding credentials and adding the Authorization header. Always use HTTPS when using basic authentication. ```java // Custom headers Unirest.get("https://api.example.com/secure") .header("Accept", "application/json") .header("x-request-id", "abc-123") .asString(); // Basic authentication (always use HTTPS!) HttpResponse res = Unirest.get("https://api.example.com/protected") .basicAuth("myUser", "s3cr3t!") .asString(); // Adds: Authorization: Basic bXlVc2VyOnMzY3IzdCE= ``` -------------------------------- ### Verify All Expectations Source: https://github.com/kong/unirest-java/blob/main/mkdocs/docs/mocks.md Validate that all registered expectations have been called at least once. This is a simple way to ensure all expected requests were made. ```java @Test void verifyAll(){ MockClient mock = MockClient.register(); mock.expect(HttpMethod.POST, "http://zombo.com") .thenReturn().withStatus(200); Unirest.post("http://zombo.com").asString().getBody(); mock.verifyAll(); } ```