杰瑞科技汇

addheaderjava如何正确使用?

Of course! The addHeader() method in Java is a fundamental part of working with HTTP requests. It's used to add a custom HTTP header to a request before it's sent to a server.

addheaderjava如何正确使用?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering the most common ways to use addHeader() in Java, from basic examples to best practices.

What is an HTTP Header?

First, let's quickly understand what HTTP headers are. They are key-value pairs sent between a client (like your Java application) and a server. They provide metadata about the request or response.

Common Request Headers:

  • User-Agent: Identifies the client software (e.g., "MyJavaApp/1.0").
  • Accept: Specifies the media types the client can understand (e.g., application/json).
  • Authorization: Contains credentials for authentication (e.g., a Bearer token).
  • Content-Type: Specifies the media type of the body of the request (e.g., application/json).

The addHeader() method allows you to add your own custom headers or override the default ones.

addheaderjava如何正确使用?-图2
(图片来源网络,侵删)

addHeader() in java.net.HttpURLConnection

This is the standard, built-in Java way to make HTTP requests, available in all Java versions.

Key Class and Method:

  • Class: java.net.HttpURLConnection
  • Method: public void addHeader(String key, String value)

Example: Making a POST Request with a Custom Header

This example demonstrates how to connect to a JSONPlaceholder API, add a custom User-Agent header, and send a JSON payload.

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class AddHeaderHttpURLConnectionExample {
    public static void main(String[] args) {
        // The URL of the API endpoint
        String urlString = "https://jsonplaceholder.typicode.com/posts";
        String postData = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";
        try {
            // 1. Create a URL object
            URL url = new URL(urlString);
            // 2. Open a connection to the URL
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 3. Set the request method (e.g., POST)
            connection.setRequestMethod("POST");
            // 4. Add headers using addHeader()
            connection.addRequestProperty("User-Agent", "MyCoolJavaApp/1.0");
            connection.addRequestProperty("Accept", "application/json");
            connection.addRequestProperty("Content-Type", "application/json");
            // 5. Enable output for the request body
            connection.setDoOutput(true);
            // 6. Write the POST data to the output stream
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = postData.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
            // 7. Get the response code
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            // You would typically read the response from the input stream here...
            // For brevity, we'll just print the headers we sent back to confirm
            System.out.println("\nRequest Headers Sent:");
            System.out.println("User-Agent: " + connection.getRequestProperty("User-Agent"));
            System.out.println("Accept: " + connection.getRequestProperty("Accept"));
            System.out.println("Content-Type: " + connection.getRequestProperty("Content-Type"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Note: HttpURLConnection has addRequestProperty() and setRequestProperty().

  • addRequestProperty(): Adds a header. If the header already exists, this method adds a new value to the existing one (creating a multi-valued header).
  • setRequestProperty(): Sets a header. If the header already exists, this method overwrites the existing value with the new one.

addHeader() in Apache HttpClient (Recommended)

For more complex applications, the built-in HttpURLConnection can be verbose. The Apache HttpClient library is more powerful, fluent, and easier to use. It's the de-facto standard for many Java projects.

Key Class and Method:

  • Class: org.apache.http.client.methods.HttpEntityEnclosingRequestBase (and its subclasses like HttpPost, HttpPut)
  • Method: public void addHeader(String name, String value)

Setup (Maven):

You need to add the dependency to your pom.xml:

<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.3.1</version> <!-- Use the latest version -->
</dependency>

Example: Making a POST Request with Headers

This example achieves the same result as the previous one but with a much cleaner API.

import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.StringEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
public class AddHeaderHttpClientExample {
    public static void main(String[] args) {
        String apiUrl = "https://jsonplaceholder.typicode.com/posts";
        String jsonPayload = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";
        // Use try-with-resources to ensure the client is closed
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 1. Create the HTTP POST request object
            HttpPost httpPost = new HttpPost(apiUrl);
            // 2. Add headers using the fluent addHeader() method
            httpPost.setHeader("User-Agent", "MyCoolJavaApp/1.0");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-Type", "application/json");
            // 3. Set the request body
            StringEntity entity = new StringEntity(jsonPayload, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 4. Execute the request and get the response
            System.out.println("Executing request: " + httpPost.getMethod() + " " + httpPost.getUri());
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 5. Get the response entity (the body)
                HttpEntity responseEntity = response.getEntity();
                // 6. Print the response status and body
                System.out.println("Response Status: " + response.getCode());
                if (responseEntity != null) {
                    String responseString = EntityUtils.toString(responseEntity);
                    System.out.println("Response Body: " + responseString);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

As you can see, Apache HttpClient provides a more object-oriented and readable approach.


addHeader() in Spring RestTemplate (Legacy)

If you are working in a Spring-based application, you might use RestTemplate. While it's now in maintenance mode (superseded by WebClient), it's still widely used.

Key Class and Method:

  • Class: org.springframework.http.HttpHeaders
  • Method: public void add(String headerName, String headerValue)

You first create an HttpHeaders object, add the headers to it, and then attach it to your RequestEntity.

Example:

import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
public class AddHeaderRestTemplateExample {
    public static void main(String[] args) {
        String url = "https://jsonplaceholder.typicode.com/posts/1";
        RestTemplate restTemplate = new RestTemplate();
        // 1. Create HttpHeaders object
        HttpHeaders headers = new HttpHeaders();
        // 2. Add headers to the HttpHeaders object
        headers.add("User-Agent", "MySpringJavaApp/1.0");
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        // 3. Create an HttpEntity with the headers (and optionally a body)
        HttpEntity<String> entity = new HttpEntity<>(headers);
        // 4. Make the GET request, passing the HttpEntity
        ResponseEntity<String> response = restTemplate.exchange(
                url, 
                HttpMethod.GET, 
                entity, 
                String.class
        );
        // 5. Print the result
        System.out.println("Status Code: " + response.getStatusCode());
        System.out.println("Response Body: " + response.getBody());
    }
}

addHeader() in Spring WebClient (Modern & Recommended for Spring)

For modern Spring applications, WebClient is the recommended non-blocking reactive HTTP client.

Key Class and Method:

  • Class: org.springframework.web.reactive.function.client.HeadersBuilder (e.g., in WebClient.RequestBodySpec)
  • Method: public H header(String headerName, String... headerValues)

The API is fluent and expressive.

Example:

import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
public class AddHeaderWebClientExample {
    public static void main(String[] args) {
        String url = "https://jsonplaceholder.typicode.com/posts/1";
        // 1. Create a WebClient instance
        WebClient webClient = WebClient.builder()
                .baseUrl(url)
                .build();
        // 2. Define the request and add headers in a fluent way
        Mono<String> response = webClient.get()
                .uri("") // Get the full URL
                .header("User-Agent", "MyModernSpringApp/1.0")
                .accept(MediaType.APPLICATION_JSON)
                .retrieve() // Execute the request
                .bodyToMono(String.class); // Extract the body as a Mono<String>
        // 3. Subscribe to the response and print it
        response.subscribe(
                body -> System.out.println("Response Body: " + body),
                error -> error.printStackTrace()
        );
        // To keep the main thread alive to see the async result
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Summary: Which one should I use?

Library / Framework Pros Cons Best For
java.net.HttpURLConnection - Built into Java (no dependencies)
- Good for simple scripts and utilities.
- Verbose and low-level API
- Lacks modern features (connection pooling, async).
Simple, standalone Java applications where you want to avoid external libraries.
Apache HttpClient - Powerful, feature-rich, and mature
- Fluent and readable API
- Excellent performance (connection pooling).
- Requires an external dependency. Most general-purpose Java applications. It's the standard choice for serious HTTP work in Java.
Spring RestTemplate - Integrates well with the Spring ecosystem
- Simplifies error handling.
- Now in maintenance mode (deprecated for new projects).
- Blocking nature.
Legacy Spring applications or simple use cases in a Spring project.
Spring WebClient - Modern, non-blocking, and reactive
- Highly performant for I/O-bound tasks
- Fluent API.
- Steeper learning curve (reactive programming concepts).
- Tied to the Spring ecosystem.
New Spring applications, especially microservices and applications requiring high throughput.
分享:
扫描分享到社交APP
上一篇
下一篇