415 (Unsupported Media Type) in $http.post method

50,334

Solution 1

I finally managed to find the cause of my error!

In my Rest-Service, I directly expected my java-class as parameter. (I thought this would be parsed/deserialized automatically). Quite naive I think... :) In order to get it working I had to:

-Expect a String as Parameter in my @POST service

-Deserialize it (using GSON)

Here is the (now working) service:

@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response save(String wo){
    if(wo == null){
        System.out.println("Could nor persist work- null");
        return Response.noContent().build();
    } else{
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HHmm:ssZ").create();
        WorkDto dto = gson.fromJson(wo, WorkDto.class);
        Work workDao = WorkTransformator.transform(dto);
        workDao.persist();
        return Response.ok().build();
    }
}

Thanks again António for your help!

Solution 2

Instead of building and sending a parsed JSON object, create a javascript object and send that in your post body. You can reuse your postData object, but try removing the "" surrounding properties names.

Try this:

    var postData = {
        status : "OPEN",
        startDate: "1338364250000",
        endDate: "1336364253400",
        workText : "Test"
};

UPDATE

Looks like the above doesn't work by itself. I thought that the Content-Type would be infered.

Can you try to do the post request this way :

    $http({
       method: 'POST',
       url: 'http://localhost:8080/service/v1/saveWork',
       data: postData,
        headers: {
            'Content-Type': 'application/json'
   }}); // complete with your success and error handlers...
        // the purpose is to try to do the post request explicitly
        // declaring the Content-Type you want to send.

UPDATE 2

If this didn't work, compose a post request using Fiddler, and check what's the response. Here's some pointers:

  • Download Fiddler2 if you dont already have it
  • Compose a request like in the screenshot below

Compose your POST like this

You can then check on the pane on the left for what was the server response code. Double click that line (Ignore the error code on the screenshot...you should be getting a 415)

Double click the line with your request

After double-clicking the response line, you can check and browse for more details on the right pane:

You can check the request and response details

If you can successfuly post with a «manufactured» JSON object then the problem resides on your Angular code. If not, it's certainly something wrong with your Rest Service configuration.

You can also inspect the details of your POSTS made with the Angular app in Fiddler2. That should give you a good insight of what's going on.

If you're into it, you can then update your question with some screenshots of your Angular app requests. That will certainly help us to help you :)

Share:
50,334
nicost
Author by

nicost

"When debugging, novices insert corrective code; Experts remove defective code" - Richard Pattis

Updated on April 20, 2020

Comments

  • nicost
    nicost about 4 years

    I'm quite new to REST and AngularJS, but after several hours of googling I couldn't find any answer to my question:

    I'm trying to do a POST request from my angularjs frontend to my backend implemented in java (using JPA).

    When I'm trying to create a json-object and to do a POST I always get the 415 (Unsupported Media Type) error.

    (Actually I don't even get "into" the scope of the service (i.E. "IN SERVICE" doesn't get printed to the console).. If I add postData.toJSON(), it actually gets "POSTed", but arrives null ...

    how do I have to format my 'postData' in Order to succesfully get POSTed?

    (I also tried to write the Date-properties without ' " ' - no luck...)

    Thank you for your help!


    FrontEnd:

    app.controller('WorkController', function($scope, $http) {

    $scope.saveWork = function () {
    
        var postData = {
        "status" : "OPEN",
        "startDate": "1338364250000",
        "endDate": "1336364253400",
        "WorkText" : "Test"
        };
    
    
        $http.post("http://localhost:8080/service/v1/saveWork", postData)
            .success(function(data, status, headers, config){
                console.log("IN SAVE WORK - SUCCESS");
                console.log(status);
            })
            .error(function(){
                console.log("ERROR IN SAVE WORK!");
            })
    }
    

    });

    Service:

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response save(WorkDto wo){
                System.out.println("IN SERVICE");
        if(ass == null){
            System.out.println("Could nor persist work- null");
            return Response.noContent().build();
        } else{
            Work workDao = WorkTransformator.transform(wo);
            workDao.persist();
            return Response.ok().build();
        }
    }
    
  • nicost
    nicost about 10 years
    hi António - like in the short-version of the post-method, this "more explicit" version results in the same : POST localhost:8080/service/v1/saveWork 415 (Unsupported Media Type)
  • António Sérgio Simões
    António Sérgio Simões about 10 years
    If I were I would use Fiddler to compose a Post request with your object and check how your Rest Service would respond to it. All this just to make sure there's nothing wrong at the Service end. I'll update my answer with some steps to test this.
  • nicost
    nicost about 10 years
    ok, i composed a request using fiddler, and i'm still getting an 415.. so - as you mentioned and as i started to fear - there must be something wrong with my rest-service... do you know if I have to do some special annotations in my WorkDto class (right now, it's a simple class with just some properties and their getters and setters)? Sorry, I'm really quite new in that... I think I need something like @XmlRootElement but for JSON, right?
  • António Sérgio Simões
    António Sérgio Simões about 10 years
    You wouldn't need nothing like that. Just think of JSON as being like a Key-Value pair dictionary. The problem is indeed your service being unable to accept the application/json content-type. You should probably open a new question with the details of your Rest service. You'll be more likely to get more specific help