Skip to lesson

GET and POST with JSON

The ShopLite app adds a product, changes its stock or cancels an order. Each of these sends data to the server, so the request needs a body and the right headers.

Accept and Content-Type headers

Content-Type is a request header that tells the server the format of the body you send, such as application/json. The Accept header tells the server which format you want back.

Set both headers on the request builder with .header(name, value). Without Content-Type, a strict API answers 415 Unsupported Media Type.

Example 1 · Content-Type missing, then present

ContentTypeDemo.javaJava
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;
/** A stand-in API that accepts a new category only when the body is labelled as JSON. */class CategoryApi {    static HttpServer start() throws IOException {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/api/v1/categories", exchange -> {            String type = exchange.getRequestHeaders().getFirst("Content-Type");            exchange.getRequestBody().readAllBytes();            if (type == null || !type.startsWith("application/json")) {                reply(exchange, 415, "{\"title\":\"Unsupported Media Type\",\"detail\":\"Send the body as application/json\"}");            } else {                reply(exchange, 201, "{\"id\":8,\"name\":\"Sports\",\"parentId\":null}");            }        });        server.start();        return server;    }
    static void reply(HttpExchange exchange, int status, String json) throws IOException {        byte[] body = json.getBytes(StandardCharsets.UTF_8);        exchange.getResponseHeaders().set("Content-Type", "application/json");        exchange.sendResponseHeaders(status, body.length);        try (OutputStream out = exchange.getResponseBody()) {            out.write(body);        }    }}
public class ContentTypeDemo {    private static final HttpClient CLIENT = HttpClient.newHttpClient();
    public static void main(String[] args) throws IOException, InterruptedException {        HttpServer server = CategoryApi.start();        URI categories = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/categories");        String json = "{\"name\":\"Sports\",\"parentId\":null}";        try {            HttpRequest withoutType = HttpRequest.newBuilder(categories)                    .POST(HttpRequest.BodyPublishers.ofString(json))          // Java adds no Content-Type                    .build();            HttpResponse<String> first = CLIENT.send(withoutType, HttpResponse.BodyHandlers.ofString());            System.out.println("Without Content-Type: " + first.statusCode() + " " + first.body());
            HttpRequest withType = HttpRequest.newBuilder(categories)                    .header("Content-Type", "application/json")              // what I am sending                    .header("Accept", "application/json")                    .POST(HttpRequest.BodyPublishers.ofString(json))                    .build();            HttpResponse<String> second = CLIENT.send(withType, HttpResponse.BodyHandlers.ofString());            System.out.println("With Content-Type:    " + second.statusCode() + " " + second.body());        } finally {            server.stop(0);        }    }}
Output
Without Content-Type: 415 {"title":"Unsupported Media Type","detail":"Send the body as application/json"}
With Content-Type:    201 {"id":8,"name":"Sports","parentId":null}

What this code does

  • The first POST has a JSON body but no Content-Type. Java does not add one, so the server refuses it with 415.
  • The second request sets Content-Type: application/json (what I send) and Accept: application/json (what I want back). The same body is now accepted with 201 Created.

Postman and curl --json add Content-Type for you, so it is easy to forget that Java does not. A request without it reaches a strict API as an unknown blob of bytes. A missing Accept is less serious, but some APIs then answer in XML or HTML.

In real projects the call works in Postman and fails from Java with 415, and the team searches for a bug in the JSON. Compare the headers first.

Fix the error

Fix the 415 error

Read the error, then pick the line that fixes it.

The POST fails with 415. Which line needs a different header?

HttpRequest request = HttpRequest.newBuilder(uri)
.header("Accept", "application/json")
.header("Content-Type", "text/plain")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();

Error

HTTP 415 Unsupported Media Type
Interview angle: 415 means "I do not understand the format of your body" (fix Content-Type); 406 means "I cannot answer in the format you asked for" (fix Accept).

POST with BodyPublishers.ofString and a Jackson-written body

A body publisher gives a request its body. BodyPublishers.ofString(json) sends a String encoded as UTF-8, and you pass the publisher to .POST(...).

Write the JSON with Jackson's writeValueAsString(record) instead of gluing text with +, then pass it to .POST(BodyPublishers.ofString(json)).

Example 2 · POST a record written by Jackson

Runs in: a Maven project with Jackson 3 (tools.jackson.core:jackson-databind)

PostJsonDemo.javaJava
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.math.BigDecimal;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import tools.jackson.databind.json.JsonMapper;
/** What the client sends to create a product (a request DTO). */record NewProduct(String sku, String name, int categoryId, BigDecimal price, int stock) {}
/** A stand-in API: prints the JSON it receives and answers 201 Created. */class ProductApi {    static HttpServer start() throws IOException {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/api/v1/products", exchange -> {            String received = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);            System.out.println("Server received: " + received);            byte[] body = ("{\"id\":16," + received.substring(1)).getBytes(StandardCharsets.UTF_8);            exchange.getResponseHeaders().set("Content-Type", "application/json");            exchange.getResponseHeaders().set("Location", "/api/v1/products/16");            exchange.sendResponseHeaders(201, body.length);            try (OutputStream out = exchange.getResponseBody()) {                out.write(body);            }        });        server.start();        return server;    }}
public class PostJsonDemo {    private static final HttpClient CLIENT = HttpClient.newHttpClient();    private static final JsonMapper JSON = JsonMapper.builder().build();   // one shared mapper
    public static void main(String[] args) throws IOException, InterruptedException {        HttpServer server = ProductApi.start();        URI products = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/products");        try {            NewProduct kurta = new NewProduct("FSH-KURTA2", "Cotton Kurta Classic", 6, new BigDecimal("1099.00"), 20);            String body = JSON.writeValueAsString(kurta);                    // record -> JSON text
            HttpRequest request = HttpRequest.newBuilder(products)                    .header("Content-Type", "application/json")                    .header("Accept", "application/json")                    .POST(HttpRequest.BodyPublishers.ofString(body))                    .build();            HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println("Status: " + response.statusCode());            System.out.println("Body:   " + response.body());        } finally {            server.stop(0);        }    }}
Output
Server received: {"sku":"FSH-KURTA2","name":"Cotton Kurta Classic","categoryId":6,"price":1099.00,"stock":20}
Status: 201
Body:   {"id":16,"sku":"FSH-KURTA2","name":"Cotton Kurta Classic","categoryId":6,"price":1099.00,"stock":20}

What this code does

  • JSON.writeValueAsString(kurta) turns the NewProduct record into JSON with the record's field names; the BigDecimal price keeps its exact value 1099.00.
  • BodyPublishers.ofString(body) sends that text as UTF-8, and the two headers say "JSON in, JSON out". The mapper is built once, like the client, because it is thread-safe too.

Example 3 · Mistake: JSON glued with + breaks on a quote

Runs in: a Maven project with Jackson 3 (tools.jackson.core:jackson-databind)

HandBuiltJsonDemo.javaJava
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.math.BigDecimal;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import tools.jackson.core.JacksonException;import tools.jackson.databind.json.JsonMapper;
record NewProduct(String sku, String name, int categoryId, BigDecimal price, int stock) {}
/** A stand-in API that checks the body really is JSON, like any real server does. */class StrictApi {    static final JsonMapper JSON = JsonMapper.builder().build();
    static HttpServer start() throws IOException {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/api/v1/products", exchange -> {            String received = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);            int status;            String json;            try {                JSON.readTree(received);                status = 201;                json = "{\"id\":16}";            } catch (JacksonException e) {                status = 400;                json = "{\"title\":\"Bad Request\",\"detail\":\"Malformed JSON\"}";            }            byte[] body = json.getBytes(StandardCharsets.UTF_8);            exchange.getResponseHeaders().set("Content-Type", "application/json");            exchange.sendResponseHeaders(status, body.length);            try (OutputStream out = exchange.getResponseBody()) {                out.write(body);            }        });        server.start();        return server;    }}
public class HandBuiltJsonDemo {    private static final HttpClient CLIENT = HttpClient.newHttpClient();    private static final JsonMapper JSON = JsonMapper.builder().build();
    static void post(URI uri, String label, String body) throws IOException, InterruptedException {        HttpRequest request = HttpRequest.newBuilder(uri)                .header("Content-Type", "application/json")                .POST(HttpRequest.BodyPublishers.ofString(body))                .build();        HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());        System.out.println(label);        System.out.println("  sent:  " + body);        System.out.println("  got:   " + response.statusCode() + " " + response.body());    }
    public static void main(String[] args) throws IOException, InterruptedException {        HttpServer server = StrictApi.start();        URI products = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/products");        String name = "Cotton Kurta \"Classic\"";                            // the name has quotes in it        try {            String glued = "{\"sku\":\"FSH-KURTA2\",\"name\":\"" + name + "\",\"categoryId\":6,"                    + "\"price\":1099.00,\"stock\":20}";            post(products, "Glued with +:", glued);
            String written = JSON.writeValueAsString(                    new NewProduct("FSH-KURTA2", name, 6, new BigDecimal("1099.00"), 20));            post(products, "Written by Jackson:", written);        } finally {            server.stop(0);        }    }}
Output
Glued with +:
  sent:  {"sku":"FSH-KURTA2","name":"Cotton Kurta "Classic"","categoryId":6,"price":1099.00,"stock":20}
  got:   400 {"title":"Bad Request","detail":"Malformed JSON"}
Written by Jackson:
  sent:  {"sku":"FSH-KURTA2","name":"Cotton Kurta \"Classic\"","categoryId":6,"price":1099.00,"stock":20}
  got:   201 {"id":16}

What this code does

  • The product name contains quotes. Glued into the JSON, the quote after Kurta ends the string early, the body is no longer valid JSON and the server answers 400.
  • Jackson writes the same name as \"Classic\", the correct JSON escape, so the server accepts it. Glued JSON works in every test until a real user types a quote or a backslash.

JSON has escaping rules: a quote inside a name must be written \", a backslash \\, a new line \n. Text glued with + breaks the moment a product name contains a quote, and the server answers 400 Bad Request. Jackson escapes every value correctly and keeps BigDecimal prices exact. Keep request bodies as small records, such as NewProduct: a record says exactly which fields the API expects.

Other body publishers:

  • BodyPublishers.ofFile(path): upload a file as the body.
  • BodyPublishers.noBody(): an explicit empty body, for example a POST that only triggers an action.

PUT, PATCH and DELETE

Use .PUT(publisher) and .DELETE(). There is no PATCH() method, so write .method("PATCH", publisher); method(name, publisher) works for any method name.

Example 4 · PUT, PATCH and DELETE on one product

WriteMethodsDemo.javaJava
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;
/** A stand-in API that prints each write it receives and answers like a REST API. */class WriteApi {    static HttpServer start() throws IOException {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/api/v1/products/9", exchange -> {            String method = exchange.getRequestMethod();            String received = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);            System.out.println("  server got " + method + (received.isEmpty() ? " (no body)" : " " + received));            if (method.equals("DELETE")) {                exchange.sendResponseHeaders(204, -1);                     // 204: no body at all                exchange.close();                return;            }            byte[] body = "{\"id\":9,\"sku\":\"BK-CLEAN\",\"price\":449.00,\"stock\":35}".getBytes(StandardCharsets.UTF_8);            exchange.getResponseHeaders().set("Content-Type", "application/json");            exchange.sendResponseHeaders(200, body.length);            try (OutputStream out = exchange.getResponseBody()) {                out.write(body);            }        });        server.start();        return server;    }}
public class WriteMethodsDemo {    private static final HttpClient CLIENT = HttpClient.newHttpClient();
    public static void main(String[] args) throws IOException, InterruptedException {        HttpServer server = WriteApi.start();        URI cleanCode = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/products/9");        try {            String fullProduct = """                    {"sku":"BK-CLEAN","name":"Clean Code","categoryId":5,"price":449.00,"stock":30}""";            HttpRequest put = HttpRequest.newBuilder(cleanCode)                    .header("Content-Type", "application/json")                    .PUT(HttpRequest.BodyPublishers.ofString(fullProduct))      // replace the whole product                    .build();            System.out.println("PUT    -> " + CLIENT.send(put, HttpResponse.BodyHandlers.ofString()).statusCode());
            HttpRequest patch = HttpRequest.newBuilder(cleanCode)                    .header("Content-Type", "application/json")                    .method("PATCH", HttpRequest.BodyPublishers.ofString("{\"stock\":35}"))                    .build();            System.out.println("PATCH  -> " + CLIENT.send(patch, HttpResponse.BodyHandlers.ofString()).statusCode());
            HttpRequest delete = HttpRequest.newBuilder(cleanCode).DELETE().build();            HttpResponse<Void> gone = CLIENT.send(delete, HttpResponse.BodyHandlers.discarding());            System.out.println("DELETE -> " + gone.statusCode() + ", body " + gone.body());        } finally {            server.stop(0);        }    }}
Output
  server got PUT {"sku":"BK-CLEAN","name":"Clean Code","categoryId":5,"price":449.00,"stock":30}
PUT    -> 200
  server got PATCH {"stock":35}
PATCH  -> 200
  server got DELETE (no body)
DELETE -> 204, body null

What this code does

  • .PUT(...) sends the whole product; .method("PATCH", ...) sends only the changed field, because the builder has no PATCH() method.
  • .DELETE() has no body. The server answers 204 No Content, so BodyHandlers.discarding() is used and the response body is null.

The difference matters to the server. PUT replaces the whole product, so it needs every field; a missing field may be set to empty. PATCH changes only the fields you send, such as {"stock":35}. DELETE usually has no body and answers 204 No Content; read such responses with BodyHandlers.discarding(), whose body is always null.

A short fixed body, such as {"stock":35}, can be a plain string or a text block. Anything built from user input or objects should go through Jackson.

Query parameters and URLEncoder

URL encoding rewrites characters that are not safe in a URL as %XX codes, so a value cannot break the query string. In Java, URLEncoder.encode(value, StandardCharsets.UTF_8) does it.

Wrap every query value in URLEncoder.encode(value, StandardCharsets.UTF_8). Encode each value, not the whole URL.

Example 5 · Glued query text versus URLEncoder

QueryEncodingDemo.javaJava
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.net.InetSocketAddress;import java.net.URI;import java.net.URLDecoder;import java.net.URLEncoder;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.StringJoiner;
/** A stand-in search endpoint that prints the parameters it decoded. */class SearchApi {    static HttpServer start() throws IOException {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/api/v1/products", exchange -> {            List<String> params = new ArrayList<>();            for (String pair : exchange.getRequestURI().getRawQuery().split("&")) {                String[] kv = pair.split("=", 2);                String value = kv.length > 1 ? URLDecoder.decode(kv[1], StandardCharsets.UTF_8) : "";                params.add(kv[0] + "=[" + value + "]");            }            System.out.println("  server saw " + params);            exchange.sendResponseHeaders(204, -1);            exchange.close();        });        server.start();        return server;    }}
public class QueryEncodingDemo {    private static final HttpClient CLIENT = HttpClient.newHttpClient();
    /** Builds "?a=1&b=2" with every value encoded. */    static String query(Map<String, String> params) {        StringJoiner joiner = new StringJoiner("&", "?", "");        params.forEach((name, value) ->                joiner.add(name + "=" + URLEncoder.encode(value, StandardCharsets.UTF_8)));        return joiner.toString();    }
    static void get(String url) throws IOException, InterruptedException {        CLIENT.send(HttpRequest.newBuilder(URI.create(url)).build(), HttpResponse.BodyHandlers.discarding());    }
    public static void main(String[] args) throws IOException, InterruptedException {        HttpServer server = SearchApi.start();        String products = "http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/products";        try {            System.out.println("1. Glued, text with &:");            get(products + "?q=" + "cover&case" + "&sort=price");
            System.out.println("2. Glued, text with a space:");            try {                get(products + "?q=" + "redmi note");            } catch (IllegalArgumentException e) {                String message = e.getMessage();                         // it also contains the full URL                System.out.println("  IllegalArgumentException: " + message.substring(0, message.indexOf(" at index")));            }
            System.out.println("3. Encoded:");            Map<String, String> params = new LinkedHashMap<>();            params.put("q", "redmi note & cover");            params.put("maxPrice", "20000");            String url = products + query(params);            System.out.println("  url ends with " + url.substring(url.indexOf('?')));            get(url);        } finally {            server.stop(0);        }    }}
Output
1. Glued, text with &:
  server saw [q=[cover], case=[], sort=[price]]
2. Glued, text with a space:
  IllegalArgumentException: Illegal character in query
3. Encoded:
  url ends with ?q=redmi+note+%26+cover&maxPrice=20000
  server saw [q=[redmi note & cover], maxPrice=[20000]]

What this code does

  • Case 1: cover&case glued into the URL splits into two parameters, so the server searches only for cover. Case 2: a space makes the URI invalid and URI.create throws.
  • Case 3: query(params) encodes each value, so redmi note & cover travels as redmi+note+%26+cover and the server decodes it back exactly.
  • A LinkedHashMap keeps the parameters in the order they were added, which makes URLs easy to read in logs.

URL encoding turns a space into +, & into %26, % into %25, and letters outside English into %XX bytes. It matters because & and = have special meanings in a query. Both bugs hide until a user types such text, which is why they reach production so often.

The clean way is one small helper that takes a Map of parameters and returns ?name=value&... with every value encoded, as in the example.

Find the bug

Find the unsafe query

Each snippet builds a search URL. Click the line that breaks for some text.

A user searches for "cover&case". Which line causes the bug?

Round 1 of 2
URLEncoder uses form encoding (space as +). Almost every server decodes + as a space in the query string. In a path segment, such as /products/{name}, + is not a space, so avoid free text in paths.

Reading the Location header after 201 Created

The Location header is a response header that holds the address of a newly created resource, such as /api/v1/customers/8. A well-designed API sends it with 201 Created.

Read it with headers().firstValue("Location"), then turn it into a full address with response.uri().resolve(location).

Example 6 · Follow the Location of a new customer

LocationDemo.javaJava
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;
/** A stand-in API: POST creates customer 8 and points to it with Location; GET reads it. */class CustomerApi {    static HttpServer start() throws IOException {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/api/v1/customers", exchange -> {            exchange.getRequestBody().readAllBytes();            if (exchange.getRequestMethod().equals("POST")) {                exchange.getResponseHeaders().set("Location", "/api/v1/customers/8");   // a relative URL                reply(exchange, 201, "{\"id\":8,\"fullName\":\"Kavya Reddy\"}");            } else {                reply(exchange, 200, "{\"id\":8,\"fullName\":\"Kavya Reddy\",\"email\":\"kavya.reddy@example.com\"}");            }        });        server.start();        return server;    }
    static void reply(HttpExchange exchange, int status, String json) throws IOException {        byte[] body = json.getBytes(StandardCharsets.UTF_8);        exchange.getResponseHeaders().set("Content-Type", "application/json");        exchange.sendResponseHeaders(status, body.length);        try (OutputStream out = exchange.getResponseBody()) {            out.write(body);        }    }}
public class LocationDemo {    private static final HttpClient CLIENT = HttpClient.newHttpClient();
    public static void main(String[] args) throws IOException, InterruptedException {        HttpServer server = CustomerApi.start();        URI customers = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/customers");        try {            String body = """                    {"fullName":"Kavya Reddy","email":"kavya.reddy@example.com","phone":"9876543209"}""";            HttpRequest create = HttpRequest.newBuilder(customers)                    .header("Content-Type", "application/json")                    .POST(HttpRequest.BodyPublishers.ofString(body))                    .build();            HttpResponse<String> created = CLIENT.send(create, HttpResponse.BodyHandlers.ofString());            System.out.println("POST status: " + created.statusCode());
            if (created.statusCode() == 201) {                String location = created.headers().firstValue("Location").orElseThrow();                URI newCustomer = created.uri().resolve(location);           // relative -> full URL                System.out.println("Location:    " + location);                System.out.println("Full URL ends with " + newCustomer.getPath());
                HttpRequest read = HttpRequest.newBuilder(newCustomer).build();                System.out.println("GET body:    " + CLIENT.send(read, HttpResponse.BodyHandlers.ofString()).body());            }        } finally {            server.stop(0);        }    }}
Output
POST status: 201
Location:    /api/v1/customers/8
Full URL ends with /api/v1/customers/8
GET body:    {"id":8,"fullName":"Kavya Reddy","email":"kavya.reddy@example.com"}

What this code does

  • The status is checked first: only a 201 has a Location. orElseThrow() turns a missing header into a clear error instead of a null.
  • created.uri().resolve(location) combines the address we called with the relative /api/v1/customers/8, giving a full URI for the follow-up GET.

The value is often relative (no http://host:port), and resolve joins it to the address you called. This is better than building "/customers/" + id yourself, because the server decides its own URLs.

Check the status before reading Location: on 400 or 409 there is no new resource and no header.

Next step

Check your understanding

11 quick questions