Composing and Sending HTTP Requests in Java
To harness the power of HTTP requests in Java, you can utilize the java.net.HttpUrlConnection class. It provides a comprehensive API for creating and dispatching HTTP requests to any web server.
Creating the Connection
To establish the connection, you'll create a URL object and use it to establish an HttpUrlConnection connection. Specify the request method (e.g., POST, GET) and set necessary headers, such as Content-Type and Content-Length.
Preparing the HTTP Request
For a POST request, format the request parameters as a query string (e.g., "name=John&age=30"). Use DataOutputStream to write the parameters to the output stream.
Sending the Request
Once the request is ready, send it by using DataOutputStream.writeBytes() to transmit the request body. The web server will respond with the requested resource.
Receiving the Response
InputStream is used to retrieve the response from the server. Use BufferedReader to read the response line by line and construct the final response body.
Sample Code
Here's a code snippet that showcases how to execute an HTTP POST request using the aforementioned techniques:
import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.io.OutputStreamWriter; import java.io.IOException; public static void sendHttpRequest() throws IOException { // Create the connection URL url = new URL("http://example.com/"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Build the request parameters String postData = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode("John", "UTF-8"); // Send the request OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(postData); writer.flush(); // Get the response int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } connection.disconnect(); }
By following these steps and utilizing the HttpUrlConnection class, you can effortlessly compose and transmit HTTP requests in your Java applications.
The above is the detailed content of How to Send HTTP Requests in Java Using `HttpUrlConnection`?. For more information, please follow other related articles on the PHP Chinese website!

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

This article explains Java's NIO API for non-blocking I/O, using Selectors and Channels to handle multiple connections efficiently with a single thread. It details the process, benefits (scalability, performance), and potential pitfalls (complexity,

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

This article details Java's socket API for network communication, covering client-server setup, data handling, and crucial considerations like resource management, error handling, and security. It also explores performance optimization techniques, i


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),