HTTP Status 415 - Unsupported Media Type when doin

2020-04-16 01:42发布

问题:

So I was trying to do a POST using REST with Postman in Chrome, but after I hit send got error

HTTP Status 415 - Unsupported Media Type

My code and part of the screen shot is included, the pair for the hashmap I tried is duration and 150. I am sure the URL is correct but don't know why the media type is not accepted.

@Path("activities")
public class ActivityResource {

    @POST
    @Path("activity")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
    public Activity createActivityParams(MultivaluedHashMap<String,String> formParams){
        return null;
    }
}

回答1:

Yeah so as I suspected, the FormMultivaluedMapProvider (which handles MultivaluedMap reading for application/x-www-form-urlencoded Content-Type only allows for MultivaluedMap<String, String> or MultivaluedMap, not MultivaluedHashMap, as you have.

Here is the source for the isReadable (which is called when the runtime looks for a MessageBodyReader to handle the combination of Java/Content-Type types.

@Override
public boolean isReadable(Class<?> type, Type genericType, 
                          Annotation[] annotations, MediaType mediaType) {
    // Only allow types MultivaluedMap<String, String> and MultivaluedMap.
    return type == MultivaluedMap.class
            && (type == genericType || mapType.equals(genericType));
}

As as side note, on the writing side, it's a different story, you can see the isWriteable method, uses isAssignableFrom, which if the isReadable had, you would be able to use the MultivaluedHashMap as your method parameter.

@Override
public boolean isWriteable(Class<?> type, Type genericType, 
                           Annotation[] annotations, MediaType mediaType) {
    return MultivaluedMap.class.isAssignableFrom(type);
}