Akka HTTP Java API: Need to create a ContentType from a string MIME type

(Brian Clapper) #1

This might just be a documentation issue. I’ve googled, I’ve search the Akka HTTP docs, and I’ve poked through the code.

A pointer—or code—would be awesome.

I have a String MIME type (such as “application/jar”). I want to create a ContentType for use in a response. I only care about a binary type, as this mapping is for a download only.

I’m stuck with the Java API. (Don’t ask.) I can easily create a mapping from a String to a MediaType. I cannot, for the life of me, figure out how—in Java—to make the final leap from a MediaType to a ContentType.

Is this even possible, without resorting to the Scala API? My client would prefer that there be no Scala in this server.

Brian Clapper

(Josep Prat) #2

Hi Brian,

Would something like this work for you? https://doc.akka.io/japi/akka-http/current/akka/http/javadsl/model/ContentTypes.html#parse-java.lang.String-

You should be able to pass any valid ContentType string as defined in the spec.
Here you can find the Mozilla page for it :slight_smile: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type

(Konrad `ktoso` Malawski) #3

Ah, you’re awesome Josep :slight_smile:
I was looking into this from the pessimistic angle and found that we do not have a 1:1 mirror of the following Scala DSL style:

  private val custom: MediaType.Binary = MediaType.customBinary("application", "wat", MediaType.Compressible)
  private val binary = ContentType(custom)
  println(s"binary = ${binary}")

This has a few missing methods in Java DSL it seems (or I’m tired).
The parse should be good enough indeed, along with https://doc.akka.io/docs/akka-http/current/common/http-model.html#registering-custom-media-types but perhaps worth a ticket to make my example be 1:1 copiable to Java as well, WDYT Josep (or did I miss some API)?

(Josep Prat) #4

You’re right, there is no 1:1.

However, there is a close match: https://doc.akka.io/japi/akka-http/current/akka/http/javadsl/model/MediaTypes.html#applicationBinary-java.lang.String-boolean-java.lang.String…- and co.
With those methods you would get a MediaType which then can be used in https://doc.akka.io/japi/akka-http/current/akka/http/javadsl/model/ContentTypes.html#create-akka.http.javadsl.model.MediaType.Binary- and others.

We could have a ticket to extend the Java API with such a factory method.

(Brian Clapper) #5

@jlprat Perfect. Thanks.

I wondered why I missed it. Then, I determined that I was using Akka HTTP 10.0.11, which doesn’t have ContentTypes.parse(). I had drilled into ContentTypes via the IDE.

My bad for not checking my version.

Thanks again.

(Josep Prat) #6

You are welcome!

(Konrad `ktoso` Malawski) #7

Yeah, agreed. Can you open a ticket about it? Thanks a ton

(Josep Prat) #8

Sure! Will do :+1:

(Josep Prat) #9