Explain Codes LogoExplain Codes Logo

How to use java.net.URLConnection to fire and handle HTTP requests

java
http-requests
java-8
httpclient
Anton ShumikhinbyAnton Shumikhin·Oct 11, 2024
TLDR

Craving a fast and furious way to HTTP requests? It's simple! Create a URL object for your endpoint. To unleash the payload of a GET request, call openConnection(), then getInputStream() to seize your data. Unchain the power of a POST request, activate setDoOutput(true), add headers or parameters using the getOutputStream(), and finally sweep your victory prize - the response from getInputStream().

GET Request: Quick and dirty!

URL url = new URL("http://example.com"); // Every journey starts with the first step, or URL InputStream response = url.openConnection().getInputStream(); // Let the force flow through you // Now, it's time for "response processing", sounds exciting!

POST Request: In and out!

URL url = new URL("http://example.com"); // Same structure, different toppings URLConnection con = url.openConnection(); // Connection is the key, no Jedi mind tricks here con.setDoOutput(true); // Activate the superpower! Outputs go brrr con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Because everyone likes to speak the same language con.getOutputStream().write("key=value".getBytes()); // Hello, server! Here's your POSTcard! InputStream response = con.getInputStream(); // Cash in your response, servers love leaving read messages // Celebrate the "response processing" victory royale!

Heads-up! Managing Request Headers

Set up HTTP headers using the setRequestProperty method, which is pretty much like choosing your coffee flavors.

con.setRequestProperty("User-Agent", "Mozilla/5.0"); // Don't we all like to pretend being a browser! con.setRequestProperty("Accept-Charset", "UTF-8"); // Speak my language, servers love UTF-8 con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); // All dressed up and ready to go in a JSON tuxedo

For handling server sessions like a Cookie Monster, use CookieManager, it does all the cookie gobbling for you.

CookieManager cookieManager = new CookieManager(); CookieHandler.setDefault(cookieManager); // Announcing the Cookie Manager, all hail!

Setting up the stage for Large File Uploads

Got a large file to upload? Use setFixedLengthStreamingMode or setChunkedStreamingMode for a seamless experience.

con.setFixedLengthStreamingMode(fileLength); // Know your size? Great, let's set it up! // or con.setChunkedStreamingMode(0); for when you like to take sudden detours

Cutting Open the Response Envelope

Unwrap your server response gift by using getHeaderFields.

Map<String, List<String>> headerFields = con.getHeaderFields(); // Secret map to your treasure

Response: A Surprise Package

After triggering a request, check the server response. Drumrolls, please:

if (((HttpURLConnection) con).getResponseCode() == HttpURLConnection.HTTP_OK) { // Hereby, I declare you successful! } else { // Some error handling magic here or we riot! }

The Secret Decoder Ring

To paint the response picture, grab the coloring instructions from the "Content-Type" header:

String contentType = con.getHeaderField("Content-Type"); String charset = null; for (String param : contentType.replace(" ", "").split(";")) { if (param.startsWith("charset=")) { charset = param.split("=", 2)[1]; // Because surprise gifts are beautiful break; } } if (charset != null) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) { // ... } }

Alternatives in the HTTP Universe

While java.net.URLConnection shines bright, other stars in the universe like Apache HttpComponents HttpClient or google-http-java-client offer advanced control and flair to your code, making them remarkable contenders.

CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://example.com"); CloseableHttpResponse response1 = httpclient.execute(httpGet); // BAM! HttpClient enters the chat!

Catching Truths and Dare Timeouts

Set timeouts to avoid waiting forever like a love-sick Romeo beneath a balcony:

con.setConnectTimeout(5000); // Time's up in 5 seconds, no more delays, even for Juliet con.setReadTimeout(5000); // Time waits for no one, not even server responses

A Souvenir: Server's Error Streams

Be proactive, play Sherlock, and find out from error streams what made the server unhappy:

if (((HttpURLConnection) con).getResponseCode() != HttpURLConnection.HTTP_OK) { InputStream error = ((HttpURLConnection) con).getErrorStream(); // Found it! Your clue in the server mystery adventure // Time to put on your detective hat and handle the errors }

Mastering POST Requests using PrintWriter

PrintWriter can make POST request construction easier, especially with text data:

PrintWriter writer = new PrintWriter(con.getOutputStream()); writer.print("param1=value1&param2=value2"); // Easy peasy lemon squeezy, POST body is ready! writer.close(); // Close the door when you leave, please!

HTTP Handling Simplified

Libraries like kevinsawicki/http-request are no less than superheroes for HTTP request handling – faster, stronger, and easier!

HttpRequest request = HttpRequest.get("http://example.com"); int response = request.code(); // One status code that rules them all! String body = request.body(); // A parcel from the server, what did you get? Map<String, String> headers = request.headers(); // Got headers? Get clues!