HTTP Request

Request lifecycle

Install AJ HTTP, not just AJ Util. Request is in com.ajaxjs.util.httpremote; Response, HttpMethod, HttpConstant and PayloadType are in com.ajaxjs.util.httpremote.model.

  1. Construct new Request(HttpMethod.GET, url) (or a method class's (HttpMethod, String) constructor). Construction does not send.
  2. Set content type, body and timeouts before init(). Defaults are 10,000 ms connect / 15,000 ms read.
  3. init(Consumer<HttpURLConnection>) creates/configures the connection. The callback should only configure headers, timeouts, redirects, etc., not start I/O. Only HTTP/HTTPS URLs are accepted.
  4. For a body, call initData() after init() and before connect().
  5. connect() reads status and response. Consume the response, then disconnect the connection in finally when managing this lifecycle yourself.

Get(String, Consumer), Delete(String, Consumer) and the data-taking Post/Put constructors send immediately. In contrast, Head(String) only configures an object: call init() and connect(). Do not send a second time after an auto-sending constructor. Requests are mutable; do not share across concurrent operations.

JSON POST with explicit lifecycle

import com.ajaxjs.util.httpremote.Request;
import com.ajaxjs.util.httpremote.model.HttpConstant;
import com.ajaxjs.util.httpremote.model.HttpMethod;
import com.ajaxjs.util.httpremote.model.Response;
import java.net.HttpURLConnection;
import java.util.Collections;

Request request = new Request(HttpMethod.POST, "https://example.com/api");
request.setContentType(HttpConstant.CONTENT_TYPE_JSON);
request.setData(Collections.<String, Object>singletonMap("name", "Ada"));
HttpURLConnection connection = request.init();
try {
    request.initData();
    Response response = request.connect();
    if (!response.isOk()) {
        throw new IllegalStateException("HTTP request failed: " + response.getHttpCode(), response.getEx());
    }
    // Parse only if this endpoint promises a JSON object.
    java.util.Map<String, Object> result = response.responseAsJson();
} finally {
    connection.disconnect();
}

Body conversion

Responses and failures

Response.isOk() means 200–299. Other statuses use the error stream, if any; a 3xx with redirects disabled may have no text. Normal HttpURLConnection redirect behavior applies unless configured otherwise. Response.isOk(Map) is a different, AJ-Spring-specific helper checking whether status.toString() equals "1".

Source: Request.java, BasePost.java, model/Response.java and AJ Util io/DataReader.java. Some TestMultipartPost assertions expect text without a trailing newline; that disagrees with the local reader. The HTTP POM resolves a versioned AJ Util dependency, so check the resolved artifact before assuming identical text behavior.

Continue with method helpers and streaming/security.