Home Java javaTutorial How to Send HTTP Requests in Java Using `HttpUrlConnection`?

How to Send HTTP Requests in Java Using `HttpUrlConnection`?

Dec 22, 2024 pm 12:14 PM

How to Send HTTP Requests in Java Using `HttpUrlConnection`?

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();
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)