0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Spring FrameworkのHttpHeaders型を使用してHTTPヘッダーを設定する場合も、改行コードや余分な空白を除去する例

Last updated at Posted at 2024-07-16

HttpHeaders型 の場合の改行コード除去

import org.springframework.http.HttpHeaders;

public class HttpHeaderCleaner {

    public static void main(String[] args) {
        // ヘッダーキーと値のペアを定義
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json\n");
        headers.add("User-Agent", "Mozilla/5.0\n");

        // 改行コードを除去
        HttpHeaders cleanHeaders = new HttpHeaders();
        headers.forEach((key, values) -> {
            values.forEach(value -> {
                String cleanValue = value.replaceAll("\\r\\n|\\r|\\n", "");
                cleanHeaders.add(key, cleanValue);
            });
        });

        // 結果を表示
        cleanHeaders.forEach((key, values) -> {
            values.forEach(value -> System.out.println(key + ": " + value));
        });
    }
}

Spring MVCのコントローラでretrunの時にhttpヘッダーの値に改行コードが含まれている場合の改行コード除去

import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.http.HttpStatus;

@RestController
public class HeaderController {

    @GetMapping("/test-header")
    public String testHeader(@RequestHeader HttpHeaders headers) {
        HttpHeaders cleanHeaders = new HttpHeaders();

        // 各ヘッダーの値から改行コードを除去
        headers.forEach((key, values) -> {
            values.forEach(value -> {
                String cleanValue = value..replaceAll("\\r\\n|\\r|\\n", "");
                cleanHeaders.add(key, cleanValue);
            });
        });

        // クリーンなヘッダーを使って処理を続ける
        return "Processed headers: " + cleanHeaders.toString();
    }
}

参考URL

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?