Skip to content
Advertisement

How to get the custom HTTP request header in server end by Java

I have a simple Google cloud function to receive the InputStream via an HTTP request.

public void service(HttpRequest request, HttpResponse response) throws Exception {

    String contentType = request.getContentType().orElse("");

    InputStream inputStream = request.getInputStream()

}

I can get the content type and input stream correctly.

However, there is also some other information, such as a SourceFileName sent in the HTTP request header from the client. I am wondering how can I get this custom header value?

I’m a .NET developer and it is very easy for me to get it in .NET:

request.Headers.TryGetValue("SourceFileName", out var sourceFileName);

Could anyone tell me how can I get it in Java?

Advertisement

Answer

You can use getHeaders method like that

BufferedWriter writer = response.getWriter();

for (Map.Entry<String,List<String>> entry : request.getHeaders().entrySet()){
    writer.write(entry.getKey() + " -> " + entry.getValue().stream().collect(Collectors.joining(",")) + "n");
}
Advertisement