Posting Form Data in Java: GET and POST, URL Encoding and Multipart
Send data to web servers with HttpURLConnection: query strings and URLEncoder/URLDecoder, POST with setDoOutput, form and JSON content types, Content-Length and streaming modes, error streams, automatic and manual redirects, cookies with CookieManager, and building multipart/form-data uploads.
kvi5hnuCode Sprout team member9 min readOn this page
Article 51 read data from web servers. Now the data flows the other way. When a user fills out an HTML form and clicks Submit, the browser sends the values of the fields to the server, and the server answers with a new page. A Java program can submit the same data without a browser, which is useful for automating interactions with web services. This article does that with HttpURLConnection, and article 53 repeats it with the modern HttpClient.
GET and POST
HTTP offers two common ways to submit form data:
- GET appends the parameters to the URL, after a
?:https://host/path?name1=value1&name2=value2. The parameters are visible in the address bar, logs and bookmarks, and GET requests should not change anything on the server. - POST sends the parameters in the request body. It's used for larger amounts of data and for requests with effects, such as placing an order.
URL encoding
Parameter names and values are encoded in the application/x-www-form-urlencoded format:
- Letters, digits and
. - _ *stay unchanged. - A space becomes
+. - Every other character is converted to UTF-8, and each byte is written as
%followed by two hex digits.
So San Francisco, CA becomes San+Francisco%2C+CA. The encoding keeps &, = and % inside values from being confused with the separators. Java's URLEncoder and URLDecoder implement it:
String encoded = URLEncoder.encode(value, StandardCharsets.UTF_8);
String decoded = URLDecoder.decode(encoded, StandardCharsets.UTF_8);
Always pass the charset. The versions without one are deprecated, because older JDKs used the platform encoding (since Java 18 the default is UTF-8, but the deprecation remains). Despite its name, URLEncoder encodes form data, not whole URLs. Use it for each name and each value separately, then join the pairs with &:
String query = params.entrySet().stream()
.map(e -> URLEncoder.encode(e.getKey(), UTF_8) + "=" + URLEncoder.encode(e.getValue(), UTF_8))
.collect(Collectors.joining("&"));
URLEncoder encodes ~ as %7E, although RFC 3986 lists it as unreserved. Servers decode both forms identically.
Posting with HttpURLConnection
To send a body, enable output before connecting, then write to the connection's output stream:
var connection = (HttpURLConnection) URI.create(url).toURL().openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
try (var out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8)) {
out.write(encodedForm);
}
int status = connection.getResponseCode();
setDoOutput(true) alone already turns a GET into a POST. The request is actually sent when you switch from writing to reading, for example by calling getResponseCode or getInputStream. By default, HttpURLConnection buffers the whole body to compute the Content-Length header. For large bodies, setFixedLengthStreamingMode(length) (when the size is known) or setChunkedStreamingMode(0) (when it isn't) send the data as you write it.
The Content-Type header tells the server how to interpret the body. Forms use application/x-www-form-urlencoded, which HttpURLConnection also sets by default for POSTs. APIs often expect JSON, so send application/json with a JSON body. The JDK has no JSON library, so either build the text yourself for simple cases (escaping quotes and backslashes) or use a library such as Jackson.
When a server reports an error, getInputStream throws, and the error page is available from getErrorStream (article 51). Check getResponseCode before choosing which stream to read.
Finding out what to send
To automate an existing web form, you need the target URL, the parameter names and sometimes particular headers. Rather than reading the page's HTML, open the browser's developer tools, switch to the network monitor, submit the form once, and inspect the request. Some sites reject requests whose User-Agent header reveals a program (the default is Java/ plus the version). You can set your own with setRequestProperty("User-Agent", ...), but respect the site's terms of use, and prefer an official API when there is one.
Redirects
Servers often answer a POST with a redirect: status 301, 302, 303, 307 or 308 and a Location header naming another URL. The Post/Redirect/Get pattern does this on purpose. After a form submission, the server redirects to a result page, so reloading it in a browser doesn't submit the form again. A 303 See Other tells the client to fetch the new location with GET.
HttpURLConnection follows redirects automatically (setFollowRedirects globally, setInstanceFollowRedirects per connection), with some limits:
- Redirects between
httpandhttps, in either direction, are never followed, for security reasons. - When a POST is redirected (other than with 307 or 308), the repeated request is a GET that starts with fresh request headers, so custom headers such as your
User-Agentare lost. Redirected GET requests keep them.
When that's a problem, turn automatic redirects off and follow them yourself:
connection.setInstanceFollowRedirects(false);
int code = connection.getResponseCode();
if (code == HTTP_MOVED_PERM || code == HTTP_MOVED_TEMP || code == HTTP_SEE_OTHER) {
String location = connection.getHeaderField("Location");
URL next = connection.getURL().toURI().resolve(location).toURL(); // Location may be relative
connection = (HttpURLConnection) next.openConnection();
// set headers again, then read the response
}
Cookies
Many sites remember a session with cookies: the server sends Set-Cookie headers, and the client returns the values in Cookie headers on later requests. HttpURLConnection handles cookies only if a cookie handler is installed:
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
The CookieManager stores cookies in a CookieStore (in memory by default) and adds them to matching requests, including automatically followed redirects. CookiePolicy.ACCEPT_ORIGINAL_SERVER, the default, accepts only cookies from the host that was contacted. ACCEPT_ALL and ACCEPT_NONE are the alternatives. Note that the default handler is global for the whole JVM.
Uploading files: multipart/form-data
HTML forms that upload files use the multipart/form-data content type. The body consists of parts separated by a boundary string that must not occur in the data. Each part has its own headers, a blank line and the content:
------boundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="title"
Quarterly report
------boundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="report.csv"
Content-Type: text/csv
region,total
north,10
------boundary7MA4YWxkTrZu0gW--
Lines end with CRLF, each boundary line is the boundary prefixed with --, and the final boundary has -- appended. The request's header announces the boundary: Content-Type: multipart/form-data; boundary=----boundary7MA4YWxkTrZu0gW. The JDK has no multipart builder, but as the demo shows, assembling one is straightforward. For binary files, write the bytes of each part to the output stream, not through a String.
The program
The demo starts a local server (the JDK's HttpServer, article 55) with a few endpoints. The client URL-encodes some tricky strings and sends a GET query. It posts an order form, which the server answers with a cookie and a 303 redirect that HttpURLConnection follows automatically. Then it repeats the post with redirects handled manually and a custom User-Agent carried over. Finally it uploads a multipart body and posts JSON. The user agent is shown with digits masked, so the output doesn't depend on the JDK version.
import com.sun.net.httpserver.*;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.*;
public class Solution {
/** Decodes "a=1&b=x+y" into an ordered map. */
static Map<String, String> parseForm(String encoded) {
var result = new LinkedHashMap<String, String>();
if (encoded == null || encoded.isEmpty()) return result;
for (String pair : encoded.split("&")) {
int eq = pair.indexOf('=');
String name = URLDecoder.decode(eq < 0 ? pair : pair.substring(0, eq), StandardCharsets.UTF_8);
String value = eq < 0 ? "" : URLDecoder.decode(pair.substring(eq + 1), StandardCharsets.UTF_8);
result.put(name, value);
}
return result;
}
/** Encodes a map as application/x-www-form-urlencoded. */
static String encodeForm(Map<String, String> params) {
return params.entrySet().stream()
.map(e -> URLEncoder.encode(e.getKey(), StandardCharsets.UTF_8) + "="
+ URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
.collect(Collectors.joining("&"));
}
static void send(HttpExchange ex, int status, String contentType, String body) throws IOException {
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().set("Content-Type", contentType);
ex.sendResponseHeaders(status, bytes.length == 0 ? -1 : bytes.length);
if (bytes.length > 0) ex.getResponseBody().write(bytes);
ex.close();
}
static HttpServer startServer() throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
server.createContext("/search", ex -> send(ex, 200, "text/plain",
ex.getRequestMethod() + " raw query: " + ex.getRequestURI().getRawQuery()
+ "\ndecoded: " + parseForm(ex.getRequestURI().getRawQuery())));
server.createContext("/order", ex -> {
String type = ex.getRequestHeaders().getFirst("Content-Type");
String body = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
Map<String, String> form = parseForm(body);
// Post/Redirect/Get: store the order, set a cookie, redirect to the result page
ex.getResponseHeaders().add("Set-Cookie", "order=" + URLEncoder.encode(form.get("item"), StandardCharsets.UTF_8) + "; Path=/");
ex.getResponseHeaders().set("Location", "/thanks");
send(ex, 303, "text/plain", "received " + type + " with " + form);
});
server.createContext("/thanks", ex -> {
String cookie = ex.getRequestHeaders().getFirst("Cookie");
send(ex, 200, "text/plain", ex.getRequestMethod() + " /thanks, cookie: " + cookie
+ ", agent: " + ex.getRequestHeaders().getFirst("User-Agent").replaceAll("[0-9.]+", "N"));
});
server.createContext("/upload", ex -> {
String type = ex.getRequestHeaders().getFirst("Content-Type");
String boundary = type.substring(type.indexOf("boundary=") + 9);
String body = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
var parts = new ArrayList<String>();
for (String part : body.split("--" + boundary)) {
int headerEnd = part.indexOf("\r\n\r\n");
if (headerEnd < 0) continue;
String headers = part.substring(0, headerEnd).strip();
String content = part.substring(headerEnd + 4, part.length() - 2); // minus trailing CRLF
String disposition = headers.lines().filter(l -> l.startsWith("Content-Disposition")).findFirst().orElse("");
parts.add(disposition.replace("Content-Disposition: form-data; ", "") + " -> " + content.length() + " chars");
}
send(ex, 200, "text/plain", String.join("\n", parts));
});
server.createContext("/api/notes", ex -> send(ex, 201, "application/json",
"{\"received\": " + new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8)
+ ", \"type\": \"" + ex.getRequestHeaders().getFirst("Content-Type") + "\"}"));
server.start();
return server;
}
static String read(HttpURLConnection c) throws IOException {
try (InputStream in = c.getResponseCode() < 400 ? c.getInputStream() : c.getErrorStream()) {
return in == null ? "" : new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
}
static HttpURLConnection post(URL url, String contentType, byte[] body, boolean streaming) throws IOException {
var c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("POST");
c.setDoOutput(true);
c.setRequestProperty("Content-Type", contentType);
if (streaming) c.setFixedLengthStreamingMode(body.length); // no buffering, but no automatic redirects
try (OutputStream out = c.getOutputStream()) {
out.write(body);
}
return c;
}
public static void main(String[] args) throws Exception {
System.out.println("--- URL encoding ---");
for (String s : List.of("San Francisco, CA", "a+b=c&d", "~user/ü*.-_", "100%"))
System.out.printf("%-20s -> %s%n", s, URLEncoder.encode(s, StandardCharsets.UTF_8));
System.out.println("decode: " + URLDecoder.decode("San+Francisco%2C+CA%20%F0%9F%8C%81", StandardCharsets.UTF_8));
var params = new LinkedHashMap<String, String>();
params.put("q", "1 Market Street, San Francisco");
params.put("hl", "de");
params.put("note", "R&D = 50%");
String query = encodeForm(params);
System.out.println("query string: " + query);
HttpServer server = startServer();
String origin = "http://127.0.0.1:" + server.getAddress().getPort();
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
try {
System.out.println("--- GET with a query ---");
var get = (HttpURLConnection) URI.create(origin + "/search?" + query).toURL().openConnection();
System.out.println(read(get));
System.out.println("--- POST a form, follow the redirect ---");
var form = new LinkedHashMap<String, String>();
form.put("item", "Tea & Biscuits");
form.put("qty", "2");
HttpURLConnection order = post(URI.create(origin + "/order").toURL(),
"application/x-www-form-urlencoded", encodeForm(form).getBytes(StandardCharsets.UTF_8), false);
int status = order.getResponseCode();
System.out.println(status + " after redirect, final URL path " + order.getURL().getPath());
System.out.println(read(order));
System.out.println("--- handling the redirect manually ---");
HttpURLConnection manual = (HttpURLConnection) URI.create(origin + "/order").toURL().openConnection();
manual.setInstanceFollowRedirects(false);
manual.setRequestMethod("POST");
manual.setDoOutput(true);
manual.setRequestProperty("User-Agent", "MyClient/2.0");
try (var out = new PrintWriter(new OutputStreamWriter(manual.getOutputStream(), StandardCharsets.UTF_8))) {
out.print(encodeForm(Map.of("item", "Coffee")));
}
int code = manual.getResponseCode();
String location = manual.getHeaderField("Location");
System.out.println(code + " " + (code == HttpURLConnection.HTTP_SEE_OTHER ? "HTTP_SEE_OTHER" : "?")
+ ", Location: " + location + ", body: " + read(manual));
URL next = manual.getURL().toURI().resolve(location).toURL();
var follow = (HttpURLConnection) next.openConnection();
follow.setRequestProperty("User-Agent", "MyClient/2.0");
System.out.println(read(follow));
System.out.println("--- multipart/form-data upload ---");
String boundary = "----boundary" + "7MA4YWxkTrZu0gW";
String crlf = "\r\n";
String multipart = "--" + boundary + crlf
+ "Content-Disposition: form-data; name=\"title\"" + crlf + crlf
+ "Quarterly report" + crlf
+ "--" + boundary + crlf
+ "Content-Disposition: form-data; name=\"file\"; filename=\"report.csv\"" + crlf
+ "Content-Type: text/csv" + crlf + crlf
+ "region,total\nnorth,10\nsouth,20\n" + crlf
+ "--" + boundary + "--" + crlf;
HttpURLConnection upload = post(URI.create(origin + "/upload").toURL(),
"multipart/form-data; boundary=" + boundary, multipart.getBytes(StandardCharsets.UTF_8), true);
System.out.println(read(upload));
System.out.println("--- POST JSON ---");
HttpURLConnection json = post(URI.create(origin + "/api/notes").toURL(), "application/json",
"{\"text\": \"buy milk\"}".getBytes(StandardCharsets.UTF_8), true);
System.out.println(json.getResponseCode() + " " + json.getContentType() + " " + read(json));
System.out.println("--- cookies kept by the CookieManager ---");
var manager = (CookieManager) CookieHandler.getDefault();
manager.getCookieStore().getCookies().stream()
.map(c -> c.getName() + "=" + c.getValue()).sorted().forEach(System.out::println);
} finally {
server.stop(0);
}
}
}
--- URL encoding ---
San Francisco, CA -> San+Francisco%2C+CA
a+b=c&d -> a%2Bb%3Dc%26d
~user/ü*.-_ -> %7Euser%2F%C3%BC*.-_
100% -> 100%25
decode: San Francisco, CA 🌁
query string: q=1+Market+Street%2C+San+Francisco&hl=de¬e=R%26D+%3D+50%25
--- GET with a query ---
GET raw query: q=1+Market+Street%2C+San+Francisco&hl=de¬e=R%26D+%3D+50%25
decoded: {q=1 Market Street, San Francisco, hl=de, note=R&D = 50%}
--- POST a form, follow the redirect ---
200 after redirect, final URL path /thanks
GET /thanks, cookie: order=Tea+%26+Biscuits, agent: Java/N
--- handling the redirect manually ---
303 HTTP_SEE_OTHER, Location: /thanks, body: received application/x-www-form-urlencoded with {item=Coffee}
GET /thanks, cookie: order=Coffee, agent: MyClient/N
--- multipart/form-data upload ---
name="title" -> 16 chars
name="file"; filename="report.csv" -> 31 chars
--- POST JSON ---
201 application/json {"received": {"text": "buy milk"}, "type": "application/json"}
--- cookies kept by the CookieManager ---
order=Coffee
Common questions
How do I send JSON without a library?
Build the string with "\"name\":\"" + escape(value) + "\"", where escape replaces \ with \\, " with \" and control characters with \n, \t or \u00XX. Set Content-Type: application/json and write the UTF-8 bytes. For anything beyond a few fields, or for parsing responses, use a JSON library such as Jackson or Gson.
Is URLEncoder the right tool for encoding a path segment?
No. It produces form encoding, where a space becomes +. In a path, + is a literal plus sign. Use the multi-argument URI constructors (article 51) for paths, and URLEncoder only for query parameters and form bodies.
Why does the server receive an empty body?
Common causes: the output stream wasn't closed or flushed before reading the response, setDoOutput(true) was set after connecting, or Content-Type doesn't match what the server expects (for example, a framework that only parses JSON). Inspect the request on the server side or with a local echo server like the demo's.
Do I need a CookieManager for APIs?
Usually not. APIs typically authenticate with tokens in an Authorization header (Bearer ...). Cookies matter when you automate a website that tracks a login session.
How do I keep cookies between program runs?
The default CookieStore lives in memory. Implement your own CookieStore that saves HttpCookie objects to a file, and pass it to new CookieManager(store, policy). Treat the file as a credential, since session cookies grant access.
API reference
| API | Purpose |
|---|---|
URLEncoder.encode(s, charset), URLDecoder.decode(s, charset) | form encoding of names and values |
HttpURLConnection.setRequestMethod("POST") | choose the method |
URLConnection.setDoOutput(true), getOutputStream() | send a request body |
setFixedLengthStreamingMode(n), setChunkedStreamingMode(0) | stream large bodies without buffering |
setRequestProperty("Content-Type", ...) | declare the body format |
getResponseCode(), getInputStream(), getErrorStream() | read the result |
setInstanceFollowRedirects(b), HttpURLConnection.setFollowRedirects(b) | redirect handling |
HTTP_MOVED_PERM, HTTP_MOVED_TEMP, HTTP_SEE_OTHER | redirect status codes |
CookieHandler.setDefault(new CookieManager(store, policy)) | enable cookie handling |
CookieManager.getCookieStore().getCookies() | inspect stored cookies |
Summary
- GET sends parameters in the URL, and POST sends them in the body.
- Encode every name and value with
URLEncoder.encode(..., UTF_8)and join the pairs with&and=. - For a POST, call
setDoOutput(true), set theContent-Type, write the body, then read the response. Use the error stream for error codes. - Streaming modes avoid buffering large bodies but disable automatic redirects.
- Redirects are followed automatically within the same protocol. Follow them manually when you need to keep headers or cross protocols.
- Install a
CookieManagerto keep cookies across requests. Multipart uploads need a boundary-separated body.
Practice Questions
Encode the parameter city with the value Zürich & Genève for a query string.
city=Z%C3%BCrich+%26+Gen%C3%A8ve. The non-ASCII letters become their UTF-8 bytes in percent form, the spaces become +, and & becomes %26, so it isn't mistaken for a separator.
Why is it wrong to call URLEncoder.encode on a complete URL such as https://example.com/a b?x=1?
URLEncoder encodes form data, so it would also encode the :, /, ? and = that structure the URL, producing https%3A%2F%2Fexample.com.... Encode only the individual parameter names and values, and build the rest of the URL with URI.
A POST that uses setFixedLengthStreamingMode fails with HttpRetryException when the server redirects. Why, and what are the options?
In streaming mode the body is sent as it's written and isn't kept, so the connection can't resend it to the new location, and automatic redirection fails. Either remove the streaming mode so that the body is buffered, or turn off automatic redirects and handle the Location header yourself.
After logging in with a POST, the next request is treated as anonymous. What is probably missing?
The session cookie from the login response isn't being sent back. HttpURLConnection ignores cookies unless a CookieHandler is installed, for example CookieHandler.setDefault(new CookieManager()). Alternatively, read the Set-Cookie header and send a Cookie header yourself.
What must a multipart/form-data body contain so that the server can separate the parts?
A boundary string that doesn't occur in the data. It's declared in the Content-Type header and appears in the body as --boundary before each part and --boundary-- at the end. Each part has headers, at least Content-Disposition with the field name (and a filename for files), then a blank line and the content, with CRLF line endings.
Previous: URIs, URLs and URLConnection in Java: Retrieving Web Data and Headers
Next: The Java HttpClient: Requests, Responses, Body Publishers and Handlers
Related reading
- URIs, URLs and URLConnection in Java: Retrieving Web Data and Headers
- Interruptible Sockets and TLS in Java: SocketChannel, Virtual Threads and SSLSocket
- Java Server Sockets: Serving Multiple Clients with Threads and Virtual Threads
- Java Sockets: Connecting to a Server, Timeouts and InetAddress
- XSL Transformations in Java: Stylesheets and the Transformer API

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.